text
stringlengths 184
4.48M
|
|---|
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace必须是dao的接口类-->
<mapper namespace="com.ydzx.dao.IStudentDao">
<!--id映射到dao类,对应其数据库具体的操作-->
<!--parameterType对应插入的数据类型,可以在mybatis.xml文件中使用别名,也可以省略-->
<insert id="insertStudent" parameterType="Student">
INSERT INTO students(t_name,t_age,score) VALUES (#{name},#{age},#{score})
</insert>
<!--插入数据获取数据库为其设置的id-->
<!--resultType为返回类型;-->
<!--keyProperty对应为Student的属性id;-->
<!--order为id生成在insert语句前后顺序关系,在MySQL中如果设置Before,则获取不到这个值;如果是oracle数据库,则需要是before;这与数据库特性有关-->
<insert id="insertStudentCacheId" parameterType="Student">
INSERT INTO students(t_name,t_age,score) VALUES (#{name},#{age},#{score})
<selectKey resultType="Integer" keyProperty="id" order="AFTER">
SELECT @@identity
</selectKey>
</insert>
<!--根据id删除-->
<delete id="deleteStudentById" parameterType="Student">
<!--#{}这里与insert不一样,这里可以放任何字符-->
DELETE FROM students WHERE t_id = #{id}
</delete>
<!--更新内容-->
<update id="updateStudent" parameterType="Student">
UPDATE students set t_name = #{name},t_age = #{age},score = #{score} WHERE t_id = #{id}
</update>
<!--查找全部数据-->
<!--resultType为指定的返回类型,不设置会报错-->
<!--注意如果数据库里查询的字段如果和类的属性名不一致,可能会导致反射失败-->
<!--比如在此例中,如果数据库的列名是t_id,t_name,t_age,那么查询到的数据将无法反射到Student类-->
<!--在此需要使用别名解决,可以将语句改成SELECT t_id,t_name name,t_age age,score FROM Students-->
<!--注意:增删改没有这个情况,不需要设置别名,只需要修改获取的参数名,因为它们没有获取数据进行映射-->
<!--另外#{name},#{age}此类的值对应的是类的属性名,不需要修改-->
<!--<select id="selectAllStudents" parameterType="Student" resultType="Student">-->
<!--SELECT id,name,age,score FROM students-->
<!--</select>-->
<!--b别名不一致还可以使用resultMap结果映射解决,再以t_id,t_name,t_age为假设-->
<resultMap id="studentMapper" type="Student">
<id column="t_id" property="id"/>
<result column="t_name" property="name"/>
<result column="t_age" property="age"/>
</resultMap>
<select id="selectAllStudents" parameterType="Student" resultMap="studentMapper">
SELECT t_id,t_name,t_age,score FROM students
</select>
<select id="selectAllStudentsMap" parameterType="Student" resultMap="studentMapper">
SELECT t_id,t_name,t_age,score FROM students
</select>
<select id="selectStudentById" parameterType="Student" resultType="Student">
SELECT t_id,t_name,t_age,score FROM students WHERE t_id = #{id}
</select>
<select id="selectStudentsByName" parameterType="Student" resultType="Student">
<!-- SELECT id,name,age,score FROM students WHERE name LIKE concat('%',#{name},'%') -->
SELECT t_id,t_name,t_age,score FROM students WHERE t_name LIKE '%' #{name} '%'
</select>
<!--多条件查询类型-->
<select id="selectStudentsByCondition" parameterType="Student" resultMap="studentMapper">
SELECT t_id,t_name,t_age,score FROM students WHERE t_name like '%' #{nameCon} '%' AND t_age > #{ageCon} AND score > #{stu.score}
</select>
<!--#{}里面可以放的信息-->
<!--1)参数对象的属性,比如#{name}-->
<!--2)随意内容,此时只起占位符作用,比如#{xxx}-->
<!--3)参数为map时的key,比如#{stu.score}-->
<!--4)参数为map时,若key所对应的value为对象,则可将该对象的属性放入-->
<!--5)参数若为数组列表,比如method(string str1,string str2,则可以使用#{0},#{1}获取对应的值-->
<!--动态查询-->
<!--需要注意的是<if test = "name != null and name != ''">中的属性指向的是Student类的属性,而不是数据库的列名-->
<!--注意如果是没有选中任何条件,可以使用where 1 = 1方式获取全部标签,但这样会造成系统开销增大;此时则可以使用where标签改进,但同时需要把SQL语句上的where删除-->
<select id="dynamicSelectStudentByCondition" parameterType="Student" resultMap="studentMapper">
SELECT t_id,t_name,t_age,score FROM students
<where>
<if test="name != null and name != ''">
t_name like '%' #{name} '%'
</if>
<if test="age > 0">
AND t_age > #{age}
</if>
</where>
</select>
<!--优先级查询-->
<!--优先级查询情况下,下面例子下,按照顺序,如果同时输入name,age,则只查询t_name LIKE name,age会自动忽略-->
<!--这有点像switch case,前面的when匹配了,自动跳出,后面的when就不匹配了,如果都没有则执行otherwise-->
<select id="dynamicSelectStudentByChoose" parameterType="Student" resultMap="studentMapper">
SELECT t_id,t_name,t_age,score FROM students
<where>
<choose>
<when test="name != null and name !=''">
AND t_name LIKE '%' #{name} '%'
</when>
<when test="age > 0">
AND t_age > #{age}
</when>
<otherwise>
AND 1=0
</otherwise>
</choose>
</where>
</select>
<!--forEach的范围查询-->
<select id="dynamicSelectStudentByForEach" parameterType="Student" resultMap="studentMapper">
SELECT t_id,t_name,t_age,score FROM students
<if test="array.length > 0">
WHERE t_id IN
<foreach collection="array" item="myId" open="(" close=")" separator=",">
#{myId}
</foreach>
</if>
</select>
<!--dynamicSelectStudentByForEachList-->
<select id="dynamicSelectStudentByForEachList" parameterType="Student" resultMap="studentMapper">
SELECT t_id,t_name,t_age,score FROM students
<if test="list.size > 0">
WHERE t_id IN
<foreach collection="list" item="myId" open="(" close=")" separator=",">
#{myId}
</foreach>
</if>
</select>
<!--list是自定义泛型-->
<select id="dynamicSelectStudentByForEachGeneric" parameterType="Student" resultMap="studentMapper">
SELECT t_id,t_name,t_age,score FROM students
<if test="list.size > 0">
WHERE t_id IN
<foreach collection="list" item="stu" open="(" close=")" separator=",">
#{stu.id}
</foreach>
</if>
</select>
</mapper>
|
import {conexion} from "../../db/atlas.js";
class Automovil{
id;
ID_Automovil;
Marca;
Modelo;
Anio;
Tipo;
Capacidad;
Precio_Diario;
constructor(){}
async connect(){
try {
const result = await conexion("automovil");
return result;
} catch (error) {
throw error;
}
};
async getAllautomoviles(){
try {
const connection = await this.connect();
const result = await connection.aggregate([
{
$project: {
"_id": 0,
"id_auto": "$ID_Automovil",
"marca_auto": "$Marca",
"modelo_auto": "$Modelo",
"año_auto": "$Anio",
"tipo_auto": "$Tipo",
"capacidad_auto": "$Capacidad",
"costo_dia": "$Precio_Diario",
}
}
]).toArray();
return result;
} catch (error) {
throw error.stack;
}
};
async getAutomovilesByID(id){
try {
const connection = await this.connect();
const result = await connection.aggregate([
{ $match: { "ID_Automovil": parseInt(id)}},
{
$project: {
"_id": 0,
"id_auto": "$ID_Automovil",
"marca_auto": "$Marca",
"modelo_auto": "$Modelo",
"año_auto": "$Anio",
"tipo_auto": "$Tipo",
"capacidad_auto": "$Capacidad",
"costo_dia": "$Precio_Diario",
}
}
]).toArray();
return result;
} catch (error) {
throw error;
}
};
async getAutomovilGrande(){
try {
const connection = await this.connect();
const result = await connection.aggregate([
{
$match: {"Capacidad": {$gt :5}}
},
{
$project: {
"_id": 0,
"id_auto": "$ID_Automovil",
"marca_auto": "$Marca",
"modelo_auto": "$Modelo",
"año_auto": "$Anio",
"tipo_auto": "$Tipo",
"capacidad_auto": "$Capacidad",
"costo_dia": "$Precio_Diario",
}
}
]).toArray();
return result;
} catch (error) {
throw error;
}
};
async getAutomovilMarcas(){
try {
const connection = await this.connect();
const result = await connection.aggregate([
{ $match: { Tipo: "Automovil" } },
{
$project: {
"_id": 0,
"id_auto": "$ID_Automovil" ,
"Marca": "$Marca",
"modelo_auto": "$Modelo",
"año_modelo": "$Anio",
"tipo_automovil": "$Tipo",
"capacidad_auto": "$Capacidad",
"precio_dia": "$Precio_Diario"
}
},
{
$group: {
_id: "$Marca",
automoviles: {
$push: "$$ROOT"
}
}
},
{
$project: {
"_id": 0,
"marca_auto": "$_id",
"automoviles": "$automoviles",
}
}
]).toArray();
return result;
} catch (error) {
throw error;
}
};
async getAutomovilDisponibleGrande(){
try {
const connection = await this.connect();
const result = await connection.aggregate([
{
$match: {
"Capacidad": {$gt :5}
}
},
{
$lookup: {
from: "sucursal_automovil",
localField: "ID_Automovil",
foreignField: "ID_Automovil_id",
pipeline: [
{
$project: {
"_id": 0,
"unidades_disponibles": "$Cantidad_Disponible"
}
}
],
as: "detalles"
}
}, {
$unwind: "$detalles"
}, {
$project: {
"_id": 0,
"id_auto": "$ID_Automovil" ,
"Marca": "$Marca",
"modelo_auto": "$Modelo",
"año_modelo": "$Anio",
"tipo_automovil": "$Tipo",
"capacidad_auto": "$Capacidad",
"precio_dia": "$Precio_Diario",
"Disponibilidad": "$detalles"
}
}
]).toArray();
return result;
} catch (error) {
throw error;
}
}
}
export { Automovil };
|
package systems;
import flixel.FlxCamera;
import flixel.FlxG;
import flixel.addons.transition.FlxTransitionableState;
import flixel.addons.ui.FlxUIState;
import flixel.addons.ui.FlxUISubState;
import flixel.group.FlxGroup.FlxTypedGroup;
import flixel.system.FlxSound;
import hscript.Global;
import lime.utils.Assets;
import openfl.system.System;
import systems.Conductor;
import ui.Notification;
class MusicBeatState extends FlxUIState {
// original variables extended from original game source
private var lastBeat:Float = 0;
private var lastStep:Float = 0;
public var allowF5:Bool = true;
public var camNotif:FlxCamera;
public var notificationGroup:FlxTypedGroup<Notification>;
override function create()
{
Global.reset();
Init.initializeSettings();
Init.arrowSkins = Init.getArrowSkins();
if (!FlxTransitionableState.skipNextTransOut)
openSubState(new Transition(0.45, true));
// clears sounds from memory
FlxG.sound.list.forEachAlive(function(sound:FlxSound)
{
FlxG.sound.list.remove(sound, true);
sound.stop();
sound.kill();
sound.destroy();
});
FlxG.sound.list.clear();
// clears all bitmaps from memory
FlxG.bitmap.dumpCache();
FlxG.bitmap.clearCache();
// clear all cache
FNFAssets.clearCache();
// run the garbage collector
System.gc();
super.create();
FlxG.cameras.reset();
camNotif = new FlxCamera();
camNotif.bgColor = 0x0;
FlxG.cameras.add(camNotif, false);
notificationGroup = new FlxTypedGroup<Notification>();
notificationGroup.cameras = [camNotif];
add(notificationGroup);
}
override function update(elapsed:Float)
{
FlxG.autoPause = Settings.get("Auto Pause");
if(FlxG.keys.justPressed.F11)
FlxG.fullscreen = !FlxG.fullscreen;
var dumb:Int = 0;
if (notificationGroup != null) {
notificationGroup.forEachAlive(function(notif:Notification) {
notif.scrollFactor.set();
notif.y = 20 + ((notif.box.height + 20) * dumb);
if(notif.shouldDie)
{
notificationGroup.remove(notif, true);
notif.kill();
notif.destroy();
}
dumb++;
});
}
updateContents();
// state refreshing
if(FlxG.keys.justPressed.F5)
if (allowF5)
resetState();
super.update(elapsed);
}
function resetState()
Main.resetState();
public function updateContents()
{
updateCurStep();
updateBeat();
// delta time bullshit
var trueStep:Int = Conductor.currentStep;
for (i in storedSteps)
if (i < oldStep)
storedSteps.remove(i);
for (i in oldStep...trueStep)
{
if (!storedSteps.contains(i) && i > 0)
{
Conductor.currentStep = i;
stepHit();
skippedSteps.push(i);
}
}
if (skippedSteps.length > 0)
{
// trace('skipped steps $skippedSteps');
skippedSteps = [];
}
Conductor.currentStep = trueStep;
//
if (oldStep != Conductor.currentStep && Conductor.currentStep > 0 && !storedSteps.contains(Conductor.currentStep))
stepHit();
oldStep = Conductor.currentStep;
}
public var oldStep:Int = 0;
var storedSteps:Array<Int> = [];
var skippedSteps:Array<Int> = [];
public function updateBeat():Void
{
Conductor.currentBeat = Math.floor(Conductor.currentStep / 4);
Conductor.currentBeatFloat = Conductor.currentStepFloat / 4;
}
public function updateCurStep():Void
{
var lastChange:BPMChangeEvent = {
stepTime: 0,
songTime: 0,
bpm: 0
}
for (i in 0...Conductor.bpmChangeMap.length)
{
if (Conductor.position >= Conductor.bpmChangeMap[i].songTime)
lastChange = Conductor.bpmChangeMap[i];
}
Conductor.currentStep = lastChange.stepTime + Math.floor((Conductor.position - lastChange.songTime) / Conductor.stepCrochet);
Conductor.currentStepFloat = lastChange.stepTime + ((Conductor.position - lastChange.songTime) / Conductor.stepCrochet);
}
public function stepHit():Void
{
if (!storedSteps.contains(Conductor.currentStep))
storedSteps.push(Conductor.currentStep);
else
{
trace('SOMETHING WENT WRONG??? STEP REPEATED ${Conductor.currentStep}');
return;
}
if (Conductor.currentStep % 4 == 0)
beatHit();
}
public function beatHit():Void
{
// used for updates when beats are hit in classes that extend this one
}
}
class MusicBeatSubState extends FlxUISubState {
public function new()
{
super();
}
private var lastBeat:Float = 0;
private var lastStep:Float = 0;
override function update(elapsed:Float)
{
updateContents();
super.update(elapsed);
}
public function updateContents()
{
updateCurStep();
updateBeat();
// delta time bullshit
var trueStep:Int = Conductor.currentStep;
for (i in storedSteps)
if (i < oldStep)
storedSteps.remove(i);
for (i in oldStep...trueStep)
{
if (!storedSteps.contains(i) && i > 0)
{
Conductor.currentStep = i;
stepHit();
skippedSteps.push(i);
}
}
if (skippedSteps.length > 0)
{
// trace('skipped steps $skippedSteps');
skippedSteps = [];
}
Conductor.currentStep = trueStep;
//
if (oldStep != Conductor.currentStep && Conductor.currentStep > 0 && !storedSteps.contains(Conductor.currentStep))
stepHit();
oldStep = Conductor.currentStep;
}
var oldStep:Int = 0;
var storedSteps:Array<Int> = [];
var skippedSteps:Array<Int> = [];
public function updateBeat():Void
{
Conductor.currentBeat = Math.floor(Conductor.currentStep / 4);
Conductor.currentBeatFloat = Conductor.currentStepFloat / 4;
}
public function updateCurStep():Void
{
var lastChange:BPMChangeEvent = {
stepTime: 0,
songTime: 0,
bpm: 0
}
for (i in 0...Conductor.bpmChangeMap.length)
{
if (Conductor.position >= Conductor.bpmChangeMap[i].songTime)
lastChange = Conductor.bpmChangeMap[i];
}
Conductor.currentStep = lastChange.stepTime + Math.floor((Conductor.position - lastChange.songTime) / Conductor.stepCrochet);
Conductor.currentStepFloat = lastChange.stepTime + ((Conductor.position - lastChange.songTime) / Conductor.stepCrochet);
}
public function stepHit():Void
{
if (!storedSteps.contains(Conductor.currentStep))
storedSteps.push(Conductor.currentStep);
else
{
trace('SOMETHING WENT WRONG??? STEP REPEATED ${Conductor.currentStep}');
return;
}
if (Conductor.currentStep % 4 == 0)
beatHit();
}
public function beatHit():Void
{
// used for updates when beats are hit in classes that extend this one
}
}
|
import datetime
from django.http import JsonResponse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render, get_object_or_404
from pet_app.decorators import vetstaff_required
from .forms import AppointmentForm, SlotCreationForm
from services.models import PetRequestService
from pets.models import Pet
from userprofile.models import Notification, User
from .models import Appointment, AppointmentSlot, book_slot, is_slot_available, get_available_slots
@login_required
def schedule_appointment_view(request, service_id):
service_request = get_object_or_404(PetRequestService, id=service_id)
user = request.user
available_slots = []
if request.method == 'POST':
appointment_form = AppointmentForm(request.POST, user=user, service_request=service_request)
if appointment_form.is_valid():
selected_slot_id = appointment_form.cleaned_data.get('slot').id # Retrieve slot ID from form data
if is_slot_available(selected_slot_id):
appointment = appointment_form.save(commit=False)
appointment.service = service_request
appointment.petowner = user
appointment.save()
book_slot(selected_slot_id)
return redirect('services:payment')
else:
messages.error(request, "Selected slot is no longer available.")
else:
appointment_form = AppointmentForm(user=user, service_request=service_request)
# If a GET request, initialize the slot queryset
appointment_form.fields['slot'].queryset = AppointmentSlot.objects.filter(
service_type=service_request.service, is_booked=False)
available_slots = appointment_form.fields['slot'].queryset
context = {
'form': appointment_form,
'available_slots': available_slots,
'service': service_request,
}
return render(request, 'appointments/schedule_appointment.html', context)
@login_required
def available_slots(request):
selected_date = request.GET.get('date')
service_id = request.GET.get('service_id', None)
# Ensure selected_date is a string in the correct format
if selected_date:
try:
# Attempt to convert selected_date to a date object and back to a string
# This is to validate that selected_date is in the correct format
#valid_date = datetime.date.fromisoformat(selected_date).isoformat()
slots = get_available_slots(service_id)
except ValueError:
# Handle the case where selected_date is not in the correct format
return JsonResponse({'error': 'Invalid date format'}, status=400)
else:
return JsonResponse({'error': 'No date provided'}, status=400)
slots_data = [
{
"id": slot.id,
"start_time": f"{slot.date} {slot.start_time.strftime('%H:%M')}",
"end_time": f"{slot.date} {slot.end_time.strftime('%H:%M')}"
}
for slot in slots
]
print("Selected Date:", selected_date, type(selected_date))
return JsonResponse(slots_data, safe=False)
@login_required
def cancel_appointment(request, appointment_id):
appointment = get_object_or_404(Appointment, id=appointment_id, petowner=request.user)
# Check if the appointment belongs to the logged-in user
if appointment.petowner != request.user:
messages.error(request, "You do not have permission to cancel this appointment.")
return redirect('dashboard:dashboard')
# Unbook the slot
slot = appointment.slot
slot.is_booked = False
slot.save()
# Delete or update the appointment as per your requirement
appointment.delete()
# For updating (e.g., setting a 'cancelled' flag):
# appointment.save()
messages.success(request, "Your appointment has been successfully cancelled.")
return redirect('dashboard:dashboard')
@login_required
def create_slot_view(request):
if request.method == 'POST':
form = SlotCreationForm(request.POST, user=request.user)
if form.is_valid():
form.save()
return redirect('dashboard:dashboard')
else:
form = SlotCreationForm(user=request.user)
return render(request, 'appointments/create_slot.html', {'form': form})
@vetstaff_required
def slots_view(request):
slots_appointments = AppointmentSlot.objects.all()
return render(request, 'appointments/slots_appointments.html', {'slots_appointments': slots_appointments})
@vetstaff_required
def delete_slots(request, appointmentslot_id):
try:
slot_appointment = AppointmentSlot.objects.get(id=appointmentslot_id)
# Check if the slot is booked before deleting
if slot_appointment.is_booked:
slot_appointment.is_booked = False
slot_appointment.save() # Save the changes to the slot appointment
slot_appointment.delete() # Delete the slot appointment
messages.success(request, "Appointment slot successfully deleted.")
except AppointmentSlot.DoesNotExist:
messages.error(request, "Appointment slot not found.")
# Redirect to a view that lists all slots, or to another appropriate page
return redirect('appointments:slots_view')
@login_required
def view_appointments(request):
user = request.user
if user.is_vetstaff:
appointments = Appointment.objects.select_related('petowner').all()
else:
appointments = Appointment.objects.filter(
petowner=request.user
).select_related('slot').order_by('slot__date')
return render(request, 'appointments/view_appointments.html', {'appointments': appointments})
|
#!/usr/bin/env Rscript
#####################################################################
##
## Read the data in
##
#####################################################################
#####################################################################
## Read in libraries and modules
#####################################################################
library (Seurat)
library (dplyr)
library (docopt) # See: https://github.com/docopt/docopt.R
source ("R/modules/constants.R")
#####################################################################
## Process arguments using docopt
#####################################################################
"Usage: print-percent-mito-filter.R --input INPUT --output OUTPUT --image IMAGE
Options:
--input INPUT Input R object
--output OUTPUT Output R object
--image IMAGE Output eps file
.
" -> options
# Retrieve the command-line arguments
opts <- docopt (options)
INPUT_ARG <- opts$input
OUTPUT_ARG <- opts$output
IMAGE_ARG <- opts$image
######################################################################
## Read in the object
######################################################################
seurat_obj <- readRDS (INPUT_ARG)
######################################################################
## Calculate the percentage of mitochondrial genes
######################################################################
# We filter out cells based on lower and upper bound on:
# - # of gene counts
# - percentage of mitochondrial genes
seurat_obj_tmp <- FilterCells (object = seurat_obj, subset.names = c("nGene", "percent.mito"), low.thresholds = c (GENE_COUNT_LOW, MITO_PERCENT_LOW), high.thresholds = c (GENE_COUNT_HIGH, MITO_PERCENT_HIGH))
# Show the effect from the filter in a 2 x 2 grid
postscript (file = IMAGE_ARG, onefile=FALSE, width=FIGURE_WIDTH, height=FIGURE_HEIGHT, paper="special", horizontal=FALSE)
par (mfrow = c(2, 2))
GenePlot (object = seurat_obj, gene1 = "nUMI", gene2 = "percent.mito")
GenePlot (object = seurat_obj, gene1 = "nUMI", gene2 = "nGene")
GenePlot (object = seurat_obj_tmp, gene1 = "nUMI", gene2 = "percent.mito")
GenePlot (object = seurat_obj_tmp, gene1 = "nUMI", gene2 = "nGene")
dev.off ()
par (mfrow = c(1,1)) # Reset mfrow
seurat_obj <- seurat_obj_tmp
######################################################################
## Save the object
######################################################################
saveRDS (seurat_obj, file = OUTPUT_ARG)
|
%
% prandtl_meyer Prandtl-Meyer function.
%
% nu = prandtl_meyer(M)
% nu = prandtl_meyer(M,gamma)
%
% See also prandtl_meyer_inverse.
%
% Copyright © 2022 Tamas Kis
% Last Update: 2022-07-28
% Website: https://tamaskis.github.io
% Contact: tamas.a.kis@outlook.com
%
% TECHNICAL DOCUMENTATION:
% https://tamaskis.github.io/files/Compressible_Flow_Relations.pdf
%
%--------------------------------------------------------------------------
%
% ------
% INPUT:
% ------
% M - (1×1 double) local Mach number, M
% gamma - (OPTIONAL) (1×1 double) specific heat ratio, γ (defaults to
% 1.4)
%
% -------
% OUTPUT:
% -------
% nu - (1×1 double) Prandtl-Meyer angle, ν [rad]
%
function nu = prandtl_meyer(M,gamma)
% defaults "gamma" to 1.4 if not specified
if (nargin < 2) || isempty(gamma)
gamma = 1.4;
end
% Prandtl-Meyer angle [rad]
nu = sqrt((gamma+1)/(gamma-1))*atan(sqrt(((gamma-1)/(gamma+1))*(M^2-...
1)))-atan(sqrt(M^2-1));
end
|
//
// ChatLogMessageCell.swift
// WeChat Clone
//
// Created by HaiboZhou on 2021/9/15.
//
import UIKit
class ChatLogMessageCell: UICollectionViewCell {
static let cellId = "ChatLogCellId"
// MARK: UI elements
lazy var messageImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.layer.cornerRadius = 6
imageView.clipsToBounds = true
// imageView.backgroundColor = .blue
return imageView
}()
lazy var messageTextView: UITextView = {
let textView = UITextView()
textView.font = .systemFont(ofSize: 18)
textView.text = "Sample message"
textView.backgroundColor = .clear
return textView
}()
lazy var textBubbleView: UIView = {
let view = UIView()
view.layer.cornerRadius = 15
view.layer.masksToBounds = true
return view
}()
lazy var profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 8
imageView.clipsToBounds = true
return imageView
}()
lazy var myImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 8
imageView.clipsToBounds = true
imageView.image = UIImage(named: "my_picture")
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
// MARK: - setupViews
func setupViews() {
// backgroundColor = .brown
addSubview(textBubbleView)
addSubview(messageTextView)
addSubview(profileImageView)
addSubview(myImageView)
addSubview(messageImageView)
let g = contentView
NSLayoutConstraint.activate([
profileImageView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 8),
profileImageView.widthAnchor.constraint(equalToConstant: 40),
profileImageView.heightAnchor.constraint(equalTo: profileImageView.widthAnchor),
profileImageView.topAnchor.constraint(equalTo: g.topAnchor),
myImageView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -8),
myImageView.widthAnchor.constraint(equalToConstant: 40),
myImageView.heightAnchor.constraint(equalTo: myImageView.widthAnchor),
myImageView.topAnchor.constraint(equalTo: g.topAnchor),
messageImageView.topAnchor.constraint(equalTo: myImageView.topAnchor),
messageImageView.trailingAnchor.constraint(equalTo: myImageView.leadingAnchor, constant: -16),
messageImageView.widthAnchor.constraint(equalTo: g.widthAnchor, multiplier: 0.5),
messageImageView.heightAnchor.constraint(equalTo: messageImageView.widthAnchor)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
import express from "express";
import { inject, injectable } from "inversify";
import { BaseMiddleware } from "inversify-express-utils";
import IVerifyTokenUseCase from "@application/usecases/token/verify/IVerifyTokenUseCase";
import AuthService from "@configuration/usecases/AuthService";
import { TYPES } from "@constants/types";
@injectable()
export default class LoggerMiddleware extends BaseMiddleware {
private readonly verifyTokenUseCase: IVerifyTokenUseCase;
constructor(@inject(TYPES.AuthService) authService: AuthService) {
super();
this.verifyTokenUseCase = authService.GetVerifyTokenUseCase();
}
public async handler(req: express.Request, res: express.Response, next: express.NextFunction) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!authHeader || !token) return res.sendStatus(401);
const tokenIsValid = await this.verifyTokenUseCase.verify(token);
if (!tokenIsValid) return res.sendStatus(403);
next();
}
}
|
rm(list=ls())
library(data.table)
library(ggplot2)
library(stargazer)
library(xtable)
setwd("G:/Shared drives/BankBusinessLines")
#### Read in Data ####
load("Data/EstimationSample.RData")
## Variable Adjustments
data[,total_deposits:=total_deposits/1e6]
data[,new_consumer_loans:=new_consumer_loans/1e6]
data[,new_commercial_loans:=new_commercial_loans/1e6]
data[,insurance_assets:=insurance_assets/1e6]
data[,investment_quantity:=investment_quantity/1e6]
data[,salary_per_asset:=salary_per_asset*1e3]
data[,premises_per_asset:=premises_per_asset*1e3]
data[,other_per_asset:=other_per_asset*1e3]
data[,total_per_asset:=total_per_asset*1e3]
data[,salaries:=salaries/1e3]
data[,premises_cost:=premises_cost/1e3]
data[,deposit_rate:=deposit_rate*100]
data[,consumer_rate:=consumer_rate*100]
data[,commercial_rate:=commercial_rate*100]
data[insurance_assets<10,insurance_price:=NA]
#### Table 1 #####
table1 = NULL
var_list = c("total_deposits","deposit_market_share","deposit_rate",
"new_consumer_loans","consumer_market_share","consumer_rate",
"new_commercial_loans","commercial_market_share","commercial_rate",
"insurance_assets","insurance_market_share","insurance_price")
var_list = c("total_deposits","new_consumer_loans","new_commercial_loans","insurance_assets","investment_quantity",
"deposit_rate","consumer_rate","commercial_rate","insurance_price","investment_price",
"salaries","premises_cost",
"salary_per_asset","premises_per_asset","other_per_asset","total_per_asset",
"branch_count","geo_coverage")
var_list_clean = c("Total Deposits (billions)",
"Consumer Loans Issued (billions)",
"Commercial Loans Issued (billions)",
"Insured Assets (billions)","Underwriting Activity (billions)",
"Deposit Interest Rate","Cons. Loan Interest Rate","Comm. Interest Rate","Ins. Premium","I Bank Fee",
"Salary (thousands)","Building Costs (thousands)",
"Salary per Asset($/million)","Building Cost per Asset ($/million)",
"Non Interest Costs per Asset ($/million)","Total Costs per Asset ($/million)",
"Number of Branches","Geographic Coverage")
# var_list_clean = var_list
for (i in 1:length(var_list)){
var = var_list[i]
data[,tempvar:=.SD,.SDcol=var]
data[tempvar==Inf|tempvar==-Inf,tempvar:=NA]
temp = data[,list(N = sum(!is.na(tempvar)),
mean=mean(tempvar,na.rm=TRUE),
p10 = quantile(tempvar,prob=0.1,na.rm=TRUE),
median = quantile(tempvar,prob=0.5,na.rm=TRUE),
p90 = quantile(tempvar,prob=0.9,na.rm=TRUE),
p99 = quantile(tempvar,prob=0.99,na.rm=TRUE)),.SDcol=var]
temp[,variable:=var_list_clean[i]]
# if (i==1){
# temp[,sample:="Full Sample"]
# }else{
# temp[,sample:=" "]
# }
table1 = rbind(table1,temp)
rm(temp)
data[,tempvar:=NULL]
}
# for (i in 1:length(var_list)){
# var = var_list[i]
# est_sample[,tempvar:=.SD,.SDcol=var]
# est_sample[tempvar==Inf|tempvar==-Inf,tempvar:=NA]
# temp = est_sample[,list(mean=mean(tempvar,na.rm=TRUE),
# p10 = quantile(tempvar,prob=0.1,na.rm=TRUE),
# median = quantile(tempvar,prob=0.5,na.rm=TRUE),
# p90 = quantile(tempvar,prob=0.9,na.rm=TRUE),
# p99 = quantile(tempvar,prob=0.99,na.rm=TRUE)),.SDcol=var]
# temp[,variable:=var_list_clean[i]]
# # if (i==1){
# # temp[,sample:="Estimation Sample"]
# # }else{
# # temp[,sample:=" "]
# # }
# table1 = rbind(table1,temp)
# rm(temp)
# est_sample[,tempvar:=NULL]
#
# }
table1 = as.data.frame(table1)
table1 = table1[,c("variable","N", "mean","p10","median","p90","p99")]
print.xtable(xtable(table1),include.rownames=FALSE)
##### Correlation Within Banks #####
vars = c("deposit_market_share","consumer_market_share","commercial_market_share",
"insurance_market_share","investment_market_share")
corr_est_banks = matrix(0,nrow=length(vars),ncol=length(vars))
rownames(corr_est_banks) = c("Deposits","Consumer Loans","Commercial Loans","Insurance","Investment")
colnames(corr_est_banks) = c("Deposits","Consumer Loans","Commercial Loans","Insurance","Investment")
for (i in 1:length(vars)){
for (j in 1:i){
data[,tempvar_i:=.SD,.SDcol=vars[i]]
data[,tempvar_j:=.SD,.SDcol=vars[j]]
c = data[!is.na(tempvar_i)&!is.na(tempvar_j),cor(tempvar_i,tempvar_j)]
corr_est_banks[j,i] = c
corr_est_banks[i,j] = c
}
}
print.xtable(xtable(corr_est_banks))
|
package com.lark.oapi.sample.apiall.corehrv2;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.corehr.v2.model.SearchBasicInfoCountryRegionSubdivisionReq;
import com.lark.oapi.service.corehr.v2.model.SearchBasicInfoCountryRegionSubdivisionReqBody;
import com.lark.oapi.service.corehr.v2.model.SearchBasicInfoCountryRegionSubdivisionResp;
// POST /open-apis/corehr/v2/basic_info/country_region_subdivisions/search
public class SearchBasicInfoCountryRegionSubdivisionSample {
public static void main(String arg[]) throws Exception {
// 构建client
Client client = Client.newBuilder("appId", "appSecret").build();
// 创建请求对象
SearchBasicInfoCountryRegionSubdivisionReq req = SearchBasicInfoCountryRegionSubdivisionReq.newBuilder()
.pageSize(100)
.pageToken("6891251722631890445")
.searchBasicInfoCountryRegionSubdivisionReqBody(SearchBasicInfoCountryRegionSubdivisionReqBody.newBuilder()
.countryRegionIdList(new String[]{})
.countryRegionSubdivisionIdList(new String[]{})
.statusList(new Integer[]{})
.build())
.build();
// 发起请求
SearchBasicInfoCountryRegionSubdivisionResp resp = client.corehr().v2().basicInfoCountryRegionSubdivision().search(req);
// 处理服务端错误
if (!resp.success()) {
System.out.println(String.format("code:%s,msg:%s,reqId:%s"
, resp.getCode(), resp.getMsg(), resp.getRequestId()));
return;
}
// 业务数据处理
System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
}
}
|
import asyncio
import fcntl
import json
import logging
import os
import stat
import subprocess # nosec
import tempfile
import time
from abc import ABCMeta, abstractmethod
from concurrent.futures import Future, ThreadPoolExecutor
from threading import Thread
import docker
import socketio
MASTER_URL: str = os.getenv("MASTER_URL", "http://localhost:8000")
sio = socketio.AsyncClient()
logger = logging.getLogger()
LOG_LEVEL = os.getenv("LOG_LEVEL", logging.DEBUG)
logging.basicConfig(level=LOG_LEVEL, format="%(message)s")
class Job(metaclass=ABCMeta):
def __init__(self, job_data: dict):
self.job_data = job_data
self.id = job_data["id"]
@abstractmethod
def stream_logs(self):
pass
@abstractmethod
def is_finished(self):
pass
@abstractmethod
def return_code(self):
pass
@abstractmethod
def run(self):
pass
class HostJob(Job):
def __init__(self, job_data: dict):
super().__init__(job_data)
self.__checking_thread = None
self.__return_code = None
self.__is_finished = False
self.__process = None
@staticmethod
def __non_block_read(output):
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.read()
except Exception:
return ""
def stream_logs(self):
return self.__non_block_read(self.__process.stdout)
def is_finished(self):
return self.__is_finished
def return_code(self):
return self.__return_code
def __check_process(self):
while True:
if self.__process.poll() is not None:
self.__is_finished = True
self.__return_code = self.__process.returncode
break
time.sleep(1)
def run(self):
job_dir_path: str = tempfile.mkdtemp(
suffix=str(self.id),
)
with open(
os.path.join(job_dir_path, f"script-{self.id}.sh"), mode="w"
) as script: # nosec
script.writelines(
"%s\n" % line for line in self.job_data["command"].splitlines()
)
script_path = script.name
current_permissions = stat.S_IMODE(os.stat(script_path).st_mode)
os.chmod(script_path, current_permissions | stat.S_IXUSR | stat.S_IXGRP)
logger.debug(f"Script prepared, {script_path}")
self.__process = subprocess.Popen( # nosec
f"cd {job_dir_path} && bash {script_path}",
shell=True,
text=True,
encoding="UTF-8",
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
logger.debug("Subprocess started")
self.__checking_thread = Thread(target=self.__check_process)
self.__checking_thread.start()
class DockerJob(Job):
def __init__(self, job_data: dict):
super().__init__(job_data)
self.__logs_streamed = False
self.__logs_thread = None
self.__saved_logs = ""
self.__container = None
def stream_logs(self):
output = self.__saved_logs
self.__saved_logs = ""
return output
def __is_run_finished(self):
self.__container.reload()
return self.__container.status == "exited"
def is_finished(self):
return self.__is_run_finished() and self.__logs_streamed
def return_code(self):
return self.__container.wait()["StatusCode"]
def __save_logs(self):
has_new_logs: bool = False
while True:
for line in self.__container.logs(timestamps=True, stream=True):
has_new_logs = True
self.__saved_logs = (
f"{self.__saved_logs}\n{line.decode('utf-8')}".strip()
)
if self.__is_run_finished():
self.__logs_streamed = True
if not has_new_logs and self.__is_run_finished():
self.__logs_streamed = True
if self.__logs_streamed:
break
has_new_logs = False
def run(self):
client = docker.from_env()
self.__container = client.containers.run(
self.job_data["image"],
command=self.job_data["command"],
detach=True,
)
self.__logs_thread = Thread(target=self.__save_logs)
self.__logs_thread.start()
class InvalidJobData(Exception):
pass
class JobFactory:
@staticmethod
def make_job(job_data: dict):
if job_data["run_type"] == "host":
return HostJob(job_data=job_data)
elif job_data["run_type"] == "docker":
return DockerJob(job_data=job_data)
else:
raise InvalidJobData()
jobs: list[Job] = []
@sio.event
async def connect():
logger.info("Connected to the Master")
@sio.event
async def disconnect():
logger.info("Disconnected from the Master")
@sio.event
async def new_job(data):
job_data = json.loads(data)
job: Job = JobFactory.make_job(job_data=job_data)
logger.info(f"New job available: {job.id}")
jobs.append(job)
async def poll_jobs() -> None:
while True:
logger.debug("Polling for jobs...")
await sio.emit("job_poll")
await asyncio.sleep(5)
def work(job: Job) -> None:
async def __execute() -> None:
job.run()
while True:
process_output = job.stream_logs()
logger.debug(f"work.while.process_output - {process_output}")
if process_output != "":
await sio.emit("logs_message", {"job": job.id, "logs": process_output})
if job.is_finished():
return_code = job.return_code()
logger.debug(f"RETURN CODE: {return_code}")
await sio.emit(
"job_finished",
{
"job_id": job.id,
"return_code": return_code,
"status": "SUCCESS" if str(return_code) == "0" else "FAIL",
},
)
break
time.sleep(1)
loop = asyncio.new_event_loop()
loop.run_until_complete(__execute())
def finished_callback(id: str, futures: dict[str, Future]) -> callable:
def callback(fn) -> None:
logger.debug(f"JOBS: {jobs}")
logger.debug(f"JOB_ID: {id}")
index = next((i for i, job in enumerate(jobs) if job.id == id), -1)
del jobs[index]
del futures[id]
logger.info(f"Job {id} done, or failed.")
return callback
async def job_worker_initializer() -> None:
pool = ThreadPoolExecutor(max_workers=2)
futures: dict[str, Future] = {}
while True:
new_jobs = {
job.id: pool.submit(work, job) for job in jobs if job.id not in futures
}
logger.debug(f"NEW {new_jobs}")
futures.update(new_jobs)
for id, future in new_jobs.items():
future.add_done_callback(finished_callback(id=id, futures=futures))
await asyncio.sleep(3)
async def main():
await sio.connect(url=MASTER_URL, auth={"api_key": os.getenv("API_KEY")})
await asyncio.gather(poll_jobs(), job_worker_initializer())
await sio.wait()
if __name__ == "__main__":
asyncio.run(main())
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Selectors</title>
<link rel="stylesheet" href="estilos.css">
<link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@500&display=swap">
<link rel="icon" href="fire-solid.svg">
</head>
<body>
<div>
<h1 class="text"><u>CSS Selectors</u></h1>
</div>
<br>
<br>
<br>
<br>
<p class="lol">A CSS selector selects the HTML element(s) you want to style.</p>
<br>
<br>
<br>
<div class="cont">
<h2>CSS Selectors</h2>
<p>CSS selectors are used to "find" (or select) the HTML elements you want to style.</p>
<p>We can divide CSS selectors into five categories:</p>
<ul>
<li>Simple selectors (select elements based on name, id, class)</li>
<li><a href="https://www.w3schools.com/css/css_combinators.asp" class="pichu">Combinator selectors</a> (select elements based on a specific relationship between them)</li>
<li><a href="https://www.w3schools.com/css/css_pseudo_classes.asp" class="pichu">Pseudo-class selectors</a> Pseudo-class selectors (select elements based on a certain state)</li>
<li><a href="https://www.w3schools.com/css/css_pseudo_elements.asp" class="pichu">selectors</a> (select and style a part of an element)</li>
<li><a href="https://www.w3schools.com/css/css_attribute_selectors.asp" class="pichu">Attribute selectors</a> (select elements based on an attribute or attribute value)</li>
</ul>
</div>
<hr class="ralla1">
<br>
<div class="cont2">
<h2 class="selector">The CSS <span class="pin1">element</span> Selector</h2>
</div>
<p class="p">The element selector selects HTML elements based on the element <span class="pin2">name</span> (body, p, h1, h5, a, div, etc.).</p>
<hr class="ralla1">
<br>
<div class="cont3">
<h2 class="selector">The CSS <span class="pin1">id</span> Selector</h2>
</div>
<p class="p">The id selector uses the id attribute of an HTML element to select a specific element.</p>
<p class="p">The id of an element is unique within a page, so the id selector is used to select one unique element!</p>
<p class="p">To select an element with a specific id, write a hash <span class="pin2">(#)</span> character, followed by the id of the element.</p>
<hr class="ralla1">
<br>
<div class="cont4">
<h2 class="selector">The CSS <span class="pin1">class</span> Selector</h2>
</div>
<br>
<p class="p">The class selector selects HTML elements with a specific class attribute.</p>
<p class="p">To select elements with a specific class, write a period <span class="pin2">(.)</span> character, followed by the class name.</p>
<hr class="ralla1">
<br>
<div class="cont5">
<h2 id="universal">The CSS <span class="pin1">Universal</span> Selector</h2>
</div>
<br>
<p class="p">The universal selector <span class="pin2">(*)</span> selects all HTML elements on the page.</p>
<p class="p">Use our <a href="https://www.w3schools.com/cssref/trysel.asp" target="_blank">CSS Selector Tester</a> to demonstrate the different selectors. </p>
<hr class="ralla1">
<div class="cont6">
<h3>CSS Syntax</h3>
</div>
<div class="cont7">
<img src="./resources/regla_css.jpg" alt="" height="754">
</div>
<div class="cont6">
<h3>All CSS Simple Selectors</h3>
</div>
<div class="cont7">
<img src="./resources/selectors.png" alt="" height="636">
</div>
</body>
</html>
|
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { DeviceService } from '../device.service';
import { ModalDismissReasons, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Devices } from '../models/devices';
import { UpdatedDevice } from '../models/updated-device';
import { DeleteDevice } from '../models/deleteDevice';
@Component({
selector: 'app-devices-component',
templateUrl: './devices-component.component.html',
styleUrls: ['./devices-component.component.css']
})
export class DevicesComponentComponent implements OnInit {
@ViewChild('change') deviceNumber:string=''
closeResult: string = '';
constructor(private service: DeviceService, private modalService: NgbModal) { }
deviceList: Devices[] = [];
ngOnInit(): void {
this.service.findAll().subscribe((data) => {
this.deviceList = data;
console.log(this.deviceList);
});
}
open(EditDevice:any) {
this.modalService.open(EditDevice, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
device: Devices = new Devices();
deletedDevice: DeleteDevice = {
planId: this.device.planId
}
// delete()
delete(planId: number): void {
this.deletedDevice.planId = planId
console.log(planId);
this.service.deleteDevice(this.deletedDevice).subscribe(result => {
console.log(result);
})
this.modalService.dismissAll("Deleted Plan!");
}
updatedDevice: UpdatedDevice = {
deviceId: this.device.deviceId,
deviceNumber: this.device.deviceNumber
}
update(deviceId: number, deviceNumber: string): void{ //add arguments to update(deviceId: number, deviceNumber: string)
this.updatedDevice.deviceId = deviceId
this.updatedDevice.deviceNumber = deviceNumber
this.service.updatePhoneNumber(this.updatedDevice).subscribe(result => {
console.log(result);
});
this.modalService.dismissAll("Updated!"); // closes the form after submitting, and updates the table
}
rnd: string | undefined = '';
Random(deviceId: number) {
// first 3 digits
const base = 3470000000;
// compute phone number
const randomNum = Math.floor(Math.random() * 10000000) + base;
// convert to string
this.rnd = randomNum.toString();
// Add hyphens
//this.rnd = this.rnd.substring(0,3) + '-' + this.rnd.substring(3,6) + '-' + this.rnd.substring(6);
//return this.rnd
let myContainer = document.getElementById('phoneNumber') as HTMLInputElement; // Add to the input field
myContainer.value = this.rnd;
this.update(deviceId, this.rnd)
}
}
|
//CARREGANDO OS MODULOS
const express = require("express"); //
const exphbs = require('express-handlebars')
const bodyParser = require('body-parser')
const RoutesController = require('./routes/adm')
const RoutesUsuario = require('./routes/userRoute')
const connectDB = require('./database')
const path = require('path')
const session = require('express-session')
const flash = require('connect-flash')
const app = express();
const passport = require('passport')
require('./helpers/auth')(passport)
const mongoose = require('mongoose')
const PORT = process.env.PORT || 3000;
//CONFIG
//Arquivos estáticos
app.use('/public', express.static(path.join(__dirname, './public')));
//Session
app.use(session({
secret: 'keyboard-cat',
resave: true,
saveUninitialized: true
}))
app.use(passport.initialize())
app.use(passport.session())
//Template engine
app.set('views', path.join(__dirname, '../src/views'));
app.engine('.hbs', exphbs({
defaultLayout: 'main',
partialsDir: path.join(app.get('views'), 'partials'),
layoutsDir: path.join(app.get('views'), 'layouts'),
extname: '.hbs',
helpers: require('./helpers/helpersHandlebars')
}));
app.set('view engine', '.hbs');
//Middlewares
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(flash())
app.use((req, res, next) => {
res.locals.success_msg = req.flash("success_msg")
res.locals.error_msg = req.flash("error_msg")
res.locals.error = req.flash("error")
res.locals.user = req.user || null
next()
})
//Body-parser
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//ROTAS
//Rotas da api - Controller
RoutesController(app)
//Rotas de LOGIN etc
RoutesUsuario(app)
//Inicia o Servidor
async function startServer(){
//await mongoose.connect("mongodb://localhost/bancoTeste")
await connectDB()
app.listen(PORT, () => {
console.log("Servidor Online na porta 3000! http://localhost:3000/");
})}
startServer()
|
package com.rakesh.OOP.Generics;
import java.util.ArrayList;
import java.util.function.Consumer;
public class LambdaFunctions {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < 5; i++) {
arr.add(i + 1);
}
// arr.forEach((item) -> System.out.println(item * 2));
Consumer<Integer> fun = (item) -> System.out.println(item * 2);
arr.forEach(fun);
Operation sum = (a, b) -> a + b;
Operation multiply = (a, b) -> a * b;
Operation subtract = (a, b) -> a - b;
LambdaFunctions calculator = new LambdaFunctions();
System.out.println((calculator.operate(4,5,sum)));
}
private int operate(int a, int b, Operation op) {
return op.operation(a, b);
}
}
interface Operation {
int operation(int a, int b);
}
|
"""Get all symbols."""
import logging
import pandas as pd
from xtb_sdk.api_client import APIClient
from xtb_sdk.consts import LOGGER_NAME
from xtb_sdk.credentials import get_credentials
from xtb_sdk.exceptions import ResponseErrorException
from xtb_sdk.request import Command, Request
from xtb_sdk.utils import inspect_dataframe
logger = logging.getLogger(LOGGER_NAME)
FORMAT = "[%(asctime)-15s][%(funcName)s:%(lineno)d] %(message)s"
logging.basicConfig(format=FORMAT)
def get_symbols():
"""Run main."""
# enter your login credentials here
credentials = get_credentials()
# create & connect to RR socket
client = APIClient(credentials, debug=False)
with client.connection() as conn:
symbols_response = conn.execute(Request(command=Command.GET_ALL_SYMBOLS))
if not symbols_response.status:
raise ResponseErrorException(
f"Symbols retrieval failed. Error code: {symbols_response.error_code}"
)
print(
f"Symbols retrieval successful. "
f"Retrived {len(symbols_response.return_data)} symbols."
)
symbols = pd.DataFrame([item.dict() for item in symbols_response.return_data])
inspect_dataframe(symbols)
symbols.to_csv("all_symbols.csv", sep=";")
if __name__ == "__main__":
get_symbols()
|
import { DateTime } from 'luxon';
import { useCallback, useMemo } from 'react';
import {
ReusableComponentsVehicleModeEnum,
RouteWithJourneyPatternStopsFragment,
ServicePatternScheduledStopPoint,
useGetRouteDetailsByIdsQuery,
} from '../../generated/graphql';
import { getRouteStopLabels } from '../../graphql';
import {
selectEditedRouteData,
selectEditedRouteIncludedStops,
selectMapRouteEditor,
selectSelectedStopId,
} from '../../redux';
import { RequiredKeys } from '../../types';
import { Priority } from '../../types/enums';
import { filterHighestPriorityCurrentStops, mapToVariables } from '../../utils';
import { useAppSelector } from '../redux';
import { useGetRoutesDisplayedInMap } from '../routes';
import { useObservationDateQueryParam } from '../urlQuery';
export type StopWithVehicleMode = RequiredKeys<
Partial<ServicePatternScheduledStopPoint>,
'vehicle_mode_on_scheduled_stop_point'
>;
const extractHighestPriorityStopsFromRoute = <
TRoute extends RouteWithJourneyPatternStopsFragment,
>(
route: TRoute,
observationDate: DateTime,
) => {
const routeStopPoints =
route.route_journey_patterns[0].ordered_scheduled_stop_point_in_journey_patterns.flatMap(
(journeyPatternStop) => journeyPatternStop.scheduled_stop_points,
) ?? [];
return filterHighestPriorityCurrentStops(
routeStopPoints,
observationDate,
// If the route is a draft, we want to select draft versions of stops if there are any
route.priority === Priority.Draft,
);
};
export const useMapStops = () => {
const { selectedRouteId } = useAppSelector(selectMapRouteEditor);
const { observationDate } = useObservationDateQueryParam();
const { displayedRouteIds } = useGetRoutesDisplayedInMap();
const selectedStopId = useAppSelector(selectSelectedStopId);
const editedRouteIncludedStops = useAppSelector(
selectEditedRouteIncludedStops,
);
const { includedStopLabels: editedRouteStopLabels } = useAppSelector(
selectEditedRouteData,
);
const displayedRoutesResult = useGetRouteDetailsByIdsQuery(
mapToVariables({ route_ids: displayedRouteIds }),
);
const displayedRoutes = useMemo(
() => displayedRoutesResult.data?.route_route || [],
[displayedRoutesResult],
);
const selectedRoute = displayedRoutes.find(
(route) => route.route_id === selectedRouteId,
);
const selectedRouteActiveStops = selectedRoute
? extractHighestPriorityStopsFromRoute(selectedRoute, observationDate)
: [];
const selectedRouteActiveStopIds = selectedRouteActiveStops.map(
(stop) => stop.scheduled_stop_point_id,
);
const editedRouteStopIds = editedRouteIncludedStops.map(
(stop) => stop.scheduled_stop_point_id,
);
const getStopVehicleMode = useCallback(
(
stop: StopWithVehicleMode,
): ReusableComponentsVehicleModeEnum | undefined => {
const stopsLabelsOnRoutes = [
...editedRouteStopLabels,
...(displayedRoutes?.flatMap((route) => getRouteStopLabels(route)) ||
[]),
];
return stop.label && stopsLabelsOnRoutes?.includes(stop.label)
? stop.vehicle_mode_on_scheduled_stop_point[0].vehicle_mode
: undefined;
},
[displayedRoutes, editedRouteStopLabels],
);
const getStopHighlighted = useCallback(
(id: UUID): boolean => {
// If editing a route, highlight stops on edited route
// Otherwise highlight stops belonging to selected route
// Also highlight selectedRoute stops until editedRouteData is loaded
const highlightedStopIds =
editedRouteIncludedStops.length > 0
? editedRouteStopIds
: selectedRouteActiveStopIds;
return highlightedStopIds?.includes(id) || selectedStopId === id;
},
[
editedRouteIncludedStops.length,
editedRouteStopIds,
selectedRouteActiveStopIds,
selectedStopId,
],
);
return { getStopVehicleMode, getStopHighlighted };
};
|
#!/usr/bin/env Rscript
# detect script being run by snakemake
# if so, make a mock commandArgs function
if ('snakemake' %in% ls()) {
logfile <- snakemake@log[[1]]
con <- file(logfile, 'w')
sink(con, type='output')
sink(con, type='message')
if (!('prevburdens' %in% names(snakemake@input)))
snakemake@input['prevburdens'] <- 'Notafile'
commandArgs <- function(...) unlist(c(
snakemake@input['mutburden'],
snakemake@input['expomat'],
snakemake@output['csv']
))
cat('Got command line arguments from snakemake:\n')
print(commandArgs())
}
args <- commandArgs(trailingOnly=TRUE)
if (length(args) != 3) {
cat("expomat.csv is the matrix of signature exposures. It *MUST* have been computed with Signature B present or else this correction will not succeed.\n")
cat("Furthermore, signature B exposure should *NOT* be present in expomat.csv.\n")
stop("usage: correct_mutburden_mda.R mutburden.csv expomat.csv out.csv")
}
mutburden.file <- args[1]
expomat.file <- args[2]
out.csv <- args[3]
if (file.exists(out.csv))
stop(paste('output file', out.csv, 'already exists, please delete it first'))
suppressMessages(library(scan2))
mutburden <- fread(mutburden.file)
expomat <- fread(expomat.file)
expo.sums <- colSums(expomat[,-1])
expo.sums <-data.table(sample=names(expo.sums), genome.burden=expo.sums)
# Rename the current genome.burden column
mutburden[, uncorrected.genome.burden := genome.burden]
mutburden$genome.burden <- NULL
# Corrected genome burden now occupies the "genome.burden" column.
mutburden <- mutburden[expo.sums,,on=.(sample)]
fwrite(mutburden, file=out.csv)
if ('snakemake' %in% ls()) {
sink()
}
|
package space.scown.adventofcode
package advent2023.problems
import lib.{Files, Problem}
import scala.annotation.tailrec
case class Day8(lines: Vector[String]) extends Problem {
override def solve1(): Unit = {
val directions = lines.head
val mapping = parseMap
@tailrec
def helper(remainingDirections: String, currentLocation: String, distance: Int): Int = {
if (remainingDirections.isEmpty) helper(directions, currentLocation, distance)
else if (currentLocation == "ZZZ") distance
else {
val nextLocation = getNextLocation(mapping, remainingDirections, currentLocation)
helper(remainingDirections.tail, nextLocation, distance + 1)
}
}
val result = helper(directions, "AAA", 0)
println(s"Result 1: $result")
}
override def solve2(): Unit = {
val directions = lines.head
val mapping = parseMap
@tailrec
def singlePathHelper(remainingDirections: String, currentLocation: String, distance: Int): (Int, String, String) = {
if (remainingDirections.isEmpty) singlePathHelper(directions, currentLocation, distance)
else if (currentLocation.last == 'Z') {
(distance, currentLocation, remainingDirections)
}
else {
val nextLocation = getNextLocation(mapping, remainingDirections, currentLocation)
singlePathHelper(remainingDirections.tail, nextLocation, distance + 1)
}
}
val initialResults = mapping.keySet.filter(k => k.last == 'A').map(k => singlePathHelper(directions, k, 0))
println(s"Initial results: ${initialResults.map(r => s"${r._1}").mkString(",")}")
val result = initialResults.map {
case (x, _, _) => x.toLong
}.reduce(lcm)
println(s"Result 2: $result")
}
private def getNextLocation(mapping: Map[String, Pair], remainingDirections: String, currentLocation: String) = {
val nextLocations = mapping(currentLocation)
val nextStep = remainingDirections.head
val nextLocation = if (nextStep == 'L') nextLocations.left else nextLocations.right
nextLocation
}
private def parseMap = {
Map.from(for (
line <- lines.tail if line.nonEmpty
) yield {
val parts = line.split(" = ")
val key = parts(0)
val lr = parts(1).replaceAll("[()]", "").split(", ")
key -> Pair(left = lr(0), right = lr(1))
})
}
private def lcm(x: Long, y: Long) = {
x * (y / gcd(x, y))
}
private def gcd(x: Long, y: Long): Long = {
@tailrec
def helper(a: Long, b: Long): Long = {
if (b == 0) a
else helper(b, a % b)
}
helper(Math.max(x, y), Math.min(x, y))
}
}
case class Pair(left: String, right: String)
object Day8 {
def main(args: Array[String]): Unit = {
val value = Files.lines("2023/day8.txt")
Day8(value).solve1()
Day8(value).solve2()
}
}
|
---
layout: post
title: "백준 알고리즘 30224번"
date: 2023-10-08 00:53:00 +0900
categories:
- Dev
- python
tag: python
comments: true
---
* this unordered seed list will be replaced by the toc
{:toc}
## 백준 알고리즘 30224번 Lucky 7
### 문제
사실이든 허구든, 어떤 사람들은 7을 행운의 숫자라고 생각합니다.
숫자가 주어지면 네 가지 값 중 하나를 출력하여 그 숫자가 얼마나 행운의 숫자인지 알아보세요.
- 숫자가 7을 포함하지 않고 7로 나눌 수 없는 경우 0을 출력합니다.
- 숫자가 7을 포함하지 않지만 7로 나눌 수 있으면 1을 출력합니다.
- 숫자에 7이 포함되어 있지만 7로 나눌 수 없는 경우 2를 출력합니다.
- 숫자에 7이 포함되어 있고 7로 나눌 수 있으면 3을 출력합니다.
### 입력
입력은 한 줄뿐이며, 1에서 10<sup>9</sup> 사이의 정수를 포함합니다.
### 출력
위에 설명된 대로 네 가지 메시지 중 하나를 인쇄합니다.
### 예제
| 입력 | 출력 |
| --- | --- |
| `25` | `0` |
| `42` | `1` |
| `170` | `2` |
| `777` | `3` |
| `1` | `0` |
| `70` | `3` |
### 풀이
```py
n = int(input())
contains_7 = '7' in str(n)
divisible_by_7 = n % 7 == 0
if not contains_7 and not divisible_by_7:
print(0)
elif not contains_7 and divisible_by_7:
print(1)
elif contains_7 and not divisible_by_7:
print(2)
else:
print(3)
```
|
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" trimDirectiveWhitespaces="false" session="false" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="my" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<my:pagetemplate title="Destination Details">
<jsp:attribute name="body">
<form method="post" action="${pageContext.request.contextPath}/destination/delete/${id}">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
<form:form method="post" action="${pageContext.request.contextPath}/destination/update"
modelAttribute="destinationUpdate" cssClass="form-horizontal">
<div class="form-group ${id_error ? 'has-error' : ''}">
<form:label path="id" cssClass="col-sm-2 control-label">Id</form:label>
<div class="col-sm-10">
<form:input path="id" cssClass="form-control" readonly="true"/>
<form:errors path="id" cssClass="help-block"/>
<p class="help-block"><form:errors path="id" cssClass="error"/></p>
</div>
</div>
<div class="form-group ${airportCode_error ? 'has-error' : ''}">
<form:label path="airportCode" cssClass="col-sm-2 control-label">Airport Code</form:label>
<div class="col-sm-10">
<form:input path="airportCode" cssClass="form-control" readonly="true"/>
<form:errors path="airportCode" cssClass="help-block"/>
<p class="help-block"><form:errors path="airportCode" cssClass="error"/></p>
</div>
</div>
<div class="form-group ${city_error ? 'has-error' : ''}">
<form:label path="city" cssClass="col-sm-2 control-label">City</form:label>
<div class="col-sm-10">
<form:input path="city" cssClass="form-control"/>
<form:errors path="city" cssClass="help-block"/>
</div>
</div>
<div class="form-group ${country_error?'has-error':''}">
<form:label path="country" cssClass="col-sm-2 control-label">Country</form:label>
<div class="col-sm-10">
<form:input path="country" cssClass="form-control"/>
<form:errors path="country" cssClass="help-block"/>
</div>
</div>
<button class="btn btn-primary" type="submit">Update</button>
</form:form>
</jsp:attribute>
</my:pagetemplate>
|
'''
CRUD:
Create, Read, Update, Delete
'''
import sqlite3
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
class Item(Resource):
parser = reqparse.RequestParser()
parser.add_argument(
'price',
type=float,
required=True,
help="This field cannot be blank!"
)
@jwt_required()
def get(self, name):
# Pull out the db query into a
# separate function ...
#
# - You can call this by using `self`
# - OR `(Classname).find...`
item = self.find_by_name(name)
if item:
return item
return {'message': 'Item not found'}, 404
@classmethod
def find_by_name(cls, name):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query = "SELECT * FROM items WHERE name=?"
result = cursor.execute(query, (name,))
row = result.fetchone()
connection.close()
# This will return "None" if row doesn't exist
if row:
return {'item': {'name': row[0], 'price': row[1]}}
def post(self, name):
# You can call a classmethod
# - `Item.find_by_name`
# - `self.find_by_name`
if self.find_by_name(name):
return {'message': '{} already exists'.format(name)}, 400
data = Item.parser.parse_args()
item = {'name': name, 'price': data['price']}
# Remove the items.append() method
# - Add in the database method
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query = "INSERT INTO items VALUES (?, ?)"
cursor.execute(query, (item['name'], item['price']))
connection.commit()
connection.close()
return item, 201
def delete(self, name):
global items
items = list(filter(lambda x: x['name'] != name, items))
return {'message': 'Item deleted'}
def put(self, name):
data = Item.parser.parse_args()
item = next(filter(lambda x: x['name'] == name, items), None)
if item is None:
item = {'name': name, 'price': data['price']}
items.append(item)
else:
item.update(data)
return item
class ItemsList(Resource):
def get(self):
return {'items': items}
|
package com.taetae98.diary.feature.compose.input
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Visibility
import androidx.compose.material.icons.rounded.VisibilityOff
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import com.taetae98.diary.feature.compose.diary.DiaryTextField
import com.taetae98.diary.feature.resource.StringResource
@Composable
fun SecureTextField(
modifier: Modifier = Modifier,
value: String,
onValueChange: (String) -> Unit,
label: String? = null,
isError: Boolean = false,
singleLine: Boolean = true,
maxLine: Int = 1,
keyboardOptions: KeyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
) {
SecureTextField(
modifier = modifier,
value = TextFieldValue(
text = value,
selection = TextRange(value.length)
),
onValueChange = { onValueChange(it.text) },
label = label,
isError = isError,
singleLine = singleLine,
maxLine = maxLine,
keyboardOptions = keyboardOptions
)
}
@Composable
fun SecureTextField(
modifier: Modifier = Modifier,
value: TextFieldValue,
onValueChange: (TextFieldValue) -> Unit,
label: String? = null,
isError: Boolean = false,
singleLine: Boolean = true,
maxLine: Int = 1,
keyboardOptions: KeyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
) {
val (isVisible, setIsVisible) = remember { mutableStateOf(false) }
DiaryTextField(
modifier = modifier,
value = value,
onValueChange = onValueChange,
label = if (label == null) {
null
} else {
{
Text(text = label)
}
},
trailingIcon = {
IconButton(onClick = { setIsVisible(isVisible.not()) }) {
Icon(
imageVector = if (isVisible) Icons.Rounded.Visibility else Icons.Rounded.VisibilityOff,
contentDescription = stringResource(id = if (isVisible) StringResource.show else StringResource.hide)
)
}
},
isError = isError,
singleLine = singleLine,
maxLines = maxLine,
visualTransformation = if (isVisible) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = keyboardOptions
)
}
|
-- Script de criação do Banco de Dados e suas Tabelas - DDL
-- Criando Banco de Dados
CREATE DATABASE SpMedGroup;
GO
-- Definindo Banco de Dados que será usado
USE SpMedGroup;
GO
-- Criando tabela com nome Clinica
CREATE TABLE Clinica (
idClinica INT PRIMARY KEY IDENTITY,
nome VARCHAR(200) UNIQUE NOT NULL,
cnpj CHAR(14) UNIQUE NOT NULL,
razaoSocial VARCHAR(200) UNIQUE NOT NULL,
enderecoLogradouro VARCHAR(200) NOT NULL,
enderecoNumero VARCHAR(200) NOT NULL,
enderecoBairro VARCHAR(200) NOT NULL,
enderecoCidade VARCHAR(200) NOT NULL,
enderecoEstado VARCHAR(200) NOT NULL,
enderecoEstado CHAR(8) NOT NULL
);
GO
-- Criando tabela de Tipo de Usuário
CREATE TABLE Tipo_Usuario (
idTipoUsuario INT PRIMARY KEY IDENTITY,
idClinica INT FOREIGN KEY REFERENCES Clinica (idClinica),
nomeTipo VARCHAR(200) NOT NULL
);
GO
-- Criando tabela de Especialidade
CREATE TABLE Especialidade (
idEspecialidade INT PRIMARY KEY IDENTITY,
idClinica INT FOREN KEY REFERENCES Clinica (idClinica),
nomeEspecialidade VARCHAR(200) NOT NULL
);
GO
-- Criando tabela de Usuário
CREATE TABLE Usuario (
idUsuario INT PRIMARY KEY IDENTITY,
idTipoUsuario INT FOREN KEY REFERENCES Tipo_Usuario (idTipoUsuario),
nomeUsuario VARCHAR(200) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
senha VARCHAR(18) NOT NULL
);
GO
-- Criando tabela Administrativo
CREATE TABLE Administrativo (
idAdministrativo PRIMARY KEY IDENTITY,
idUsuario FOREN KEY REFERENCES Usuario (idUsuario),
descricao VARCHAR(100)
);
GO
-- Criando tabela de Médico
CREATE TABLE Medico (
idMedico INT PRIMARY KEY IDENTITY,
idUsuario INT FOREN KEY REFERENCES Usuario (idUsuario),
idEspecialidade INT FOREN KEY REFERENCES Especialidade (idEspecialidade),
CRM CHAR(7) UNIQUE NOT NULL
);
GO
-- Criando tabela de Paciente
CREATE TABLE PACIENTE (
idPaciente INT PRIMARY KEY IDENTITY,
idUsuario INT FOREN KEY REFERENCES Usuario (idUsuario),
RG CHAR(9) UNIQUE NOT NULL,
CPF CHAR(11) UNIQUE NOT NULL,
enderecoLogradouro VARCHAR(200) NOT NULL,
enderecoNumero VARCHAR(200) NOT NULL,
enderecoBairro VARCHAR(200) NOT NULL,
enderecoCidade VARCHAR(200) NOT NULL,
enderecoEstado VARCHAR(200) NOT NULL,
enderecoCEP CHAR(8) NOT NULL
);
GO
-- Criando tabela Consulta
CREATE TABLE Consulta (
idConsulta INT PRIMARY KEY IDENTITY,
idMedico INT FOREN KEY REFERENCES Medico (idMedico),
idPaciente INT FOREN KEY REFERENCES Paciente (idPaciente),
dataConsulta DATE NOT NULL,
situação VARCHAR(15) NOT NULL,
descricaoProntuario VARCHAR(255)
);
GO
|
import 'package:hive/hive.dart';
part 'cart_item.g.dart';
@HiveType(typeId: 1)
class CartItem extends HiveObject{
@HiveField(0)
late String id;
@HiveField(1)
late String title;
@HiveField(2)
late int quantity;
@HiveField(3)
late String imageUrl;
@HiveField(4)
late int total;
@HiveField(5)
late int price;
CartItem({
required this.imageUrl,
required this.title,
required this.id,
required this.quantity,
required this.total,
required this.price
});
factory CartItem.fromJson(Map<String, dynamic> json){
return CartItem(
id: json['id'],
imageUrl: json['imageUrl'],
quantity: json['quantity'],
title: json['title'],
total: json['total'],
price: json['price']
);
}
Map<String, dynamic> toJson(){
return {
'id': this.id,
'imageUrl': this.imageUrl,
'quantity': this.quantity,
'title': this.title,
'total': this.total,
'price': this.price
};
}
}
|
#pragma once
#include<iostream>
class Creature {
public:
virtual ~Creature(){}
virtual Creature* Clone() { return nullptr; }
Creature() = default;
Creature(int hp, int speed, int attack) : HitPoints{ hp }, Speed{ speed }, Attack{ attack } {}
int getHP() const { return HitPoints; }
int getSpeed() const { return Speed; }
int getAttack() const { return Attack; }
protected:
int HitPoints{ 0 };
int Speed{ 0 };
int Attack{ 0 };
};
class Dog : public Creature {
public:
Dog() { HitPoints = 3; Speed = 3; Attack = 3; }
void Bark() const { std::cout << "Woof!!\n"; }
};
class Cat : public Creature {
public:
Cat() { HitPoints = 2; Speed = 2; Attack = 2; }
void Meow() const { std::cout << "Meow!!\n"; }
};
class Mouse : public Creature {
public:
Mouse() { HitPoints = 1; Speed = 1; Attack = 1; }
void Squeak() const { std::cout << "eekeekek!!\n"; }
};
// Prototype Creature
class Lizard : public Creature {
public:
Lizard(int hp, int speed, int attack) : Creature{ hp , speed, attack} {}
Creature* Clone() { return new Lizard( HitPoints, Speed, Attack ); }
void Hiss() const { std::cout << "sssssssssssssssss\n"; }
};
|
package com.azuyamat.blixify.commands.impl.pickaxe
import com.azuyamat.blixify.commands.annotations.Tab
import com.azuyamat.blixify.commands.annotations.SubCommand
import com.azuyamat.blixify.pickaxeManager
import org.bukkit.entity.Player
import com.azuyamat.blixify.commands.annotations.Command
import com.azuyamat.blixify.helpers.parse
import com.azuyamat.blixify.pickaxe.updateLore
@Command(
name = "pickaxes",
description = "Pickaxe admin command",
aliases = ["picks"],
permission = "blixify.pickaxes",
)
class PickaxesCommand {
fun onCommand(sender: Player): Boolean {
sender.sendMessage("<gray>Use this command to manage pickaxes <red>(ADMIN ONLY)".parse(true))
return true
}
@SubCommand("list", "List pickaxes")
fun list(sender: Player): Boolean {
sender.sendMessage("<gray>Pickaxes (${pickaxeManager.pickaxes.size}):".parse(true))
sender.sendMessage(pickaxeManager.pickaxes.map { "<gray>${it.key}" }.joinToString("<gray>, ").parse(true))
return true
}
@SubCommand("reload", "Reload pickaxe registry")
fun reload(sender: Player): Boolean {
sender.sendMessage("<gray>Reloading pickaxe registry...".parse(true))
pickaxeManager.reload()
sender.sendMessage("<gray>Reloaded pickaxe registry!".parse(true))
return true
}
@SubCommand("give", "Give pickaxe to player")
fun give(player: Player, @Tab("pickaxe") id: String, receiver: Player?) {
val pickaxe = pickaxeManager.getPickaxe(id) ?: run {
player.sendMessage("Pickaxe $id not found")
return
}
val target = receiver ?: player
val item = pickaxe.create().updateLore(target)
target.inventory.addItem(item)
player.sendMessage("<gray>Gave pickaxe <main>$id <gray>to <main>${target.name}".parse(true))
target.sendMessage("<gray>You have received a <main>${pickaxe.id}<gray> pickaxe!".parse(true))
}
}
|
import * as React from "react";
import Avatar from "@mui/material/Avatar";
import Button from "@mui/material/Button";
import CssBaseline from "@mui/material/CssBaseline";
import TextField from "@mui/material/TextField";
import Link from "@mui/material/Link";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import Typography from "@mui/material/Typography";
import Container from "@mui/material/Container";
import axios from 'axios';
import { useDispatch } from "react-redux";
import { login } from "../state/action-creators";
import { useNavigate } from "react-router-dom";
import { useState } from "react";
import OtpModal from "./OtpModal";
import { Alert } from "@mui/material";
const SERVER = process.env.REACT_APP_AUTH_SERVER;
export default function SignUp() {
const dispatch = useDispatch();
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(false);
const [isOtpModalOpen, setIsOtpModalOpen] = useState(false);
const [email, setEmail] = useState();
const [formData, setFormData] = useState();
const [alertMsg, setAlertMsg] = useState();
const checkUser = async (email)=>{
const res = await axios.get(`${SERVER}api/verifications/checkUser?email=${email}`)
return res.data;
}
const handleSubmit = async (e) => {
e.preventDefault();
setIsLoading(true);
setAlertMsg(null);
setFormData(new FormData(e.currentTarget));
const data = new FormData(e.currentTarget);
const temp = data.get('email');
setEmail(temp);
try{
const shouldRegister = await checkUser(temp);
if(shouldRegister.success){
setIsOtpModalOpen(true);
}
else{
setAlertMsg(shouldRegister.error);
}
}
catch (error) {
setAlertMsg(error.message);
}
finally{
setIsLoading(false);
}
};
const createUser = async () => {
const firstName = formData.get("firstName");
const lastName = formData.get("lastName");
const password = formData.get("password");
const response = await fetch(`${SERVER}api/auth/createuser`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ firstName, lastName, email, password }),
});
const json = await response.json();
setIsLoading(false);
if (json.success) {
// Save the auth token and redirect
localStorage.setItem("token", json.authtoken);
dispatch(login(json.authtoken));
navigate("/");
} else {
// props.showAlert("Invalid Details","danger");
console.log("failse");
}
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<Avatar sx={{ m: 1, bgcolor: "secondary.main" }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
{alertMsg && <Alert severity="error">{alertMsg}</Alert>}
<Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 3 }}>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<TextField
autoComplete="given-name"
name="firstName"
required
fullWidth
id="firstName"
label="First Name"
autoFocus
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
required
fullWidth
id="lastName"
label="Last Name"
name="lastName"
autoComplete="family-name"
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="new-password"
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
disabled={isLoading}
>
{isLoading ? "Signing Up..." : "Sign Up"}
</Button>
<Grid container justifyContent="flex-end">
<Grid item>
<Link
href="/login"
variant="body2"
onClick={(event) => {
event.preventDefault();
navigate("/login");
}}
>
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</Box>
{alertMsg && <Alert severity="error">{alertMsg}</Alert>}
</Box>
{isOtpModalOpen && <OtpModal email={email} open={isOtpModalOpen} setOpen={setIsOtpModalOpen} next={createUser}/>}
</Container>
);
}
|
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { JuegoService } from './juego.service';
import { HttpClientModule } from '@angular/common/http';
import { ListaJuegosComponent } from './lista-juegos/lista-juegos.component';
import { HeaderComponent } from './header/header.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MatCardModule} from '@angular/material/card';
import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
import {MatToolbarModule} from '@angular/material/toolbar';
import { SearchbarComponent } from './searchbar/searchbar.component';
import { MatIcon } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { FooterComponent } from './footer/footer.component';
import { NavComponent } from './nav/nav.component';
import {NgIf} from '@angular/common';
import {MatSidenavModule} from '@angular/material/sidenav';
import { FormBuilder } from '@angular/forms';
import { FormGroup } from '@angular/forms';
import { BuscadorPipe } from './buscador.pipe';
import { BuscadorJuegosComponent } from './buscador-juegos/buscador-juegos.component';
@NgModule({
declarations: [
AppComponent,
ListaJuegosComponent,
HeaderComponent,
SearchbarComponent,
FooterComponent,
BuscadorPipe,
BuscadorJuegosComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
MatButtonModule,
MatCardModule,
MatIconModule,
MatToolbarModule,
MatFormFieldModule,
FormsModule,
MatInputModule,
MatSelectModule,
NgIf,
MatSidenavModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(private JuegoService: JuegoService){}
juegos: any = [];
getJuegos(): void {
this.JuegoService.getJuegos()
.subscribe(juegos => this.juegos = juegos);
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-model的修饰符</title>
</head>
<body>
<div id="app">
<!-- lazy表示可以让数据在失去焦点或回车时才会更新,而不是像默认那样实时更新-->
<input type="text" v-model.lazy="message">
<h2>{{message}}</h2>
<!-- number可以让输入框中输入的内容转变为number类型-->
<input type="number" v-model.number="age">
<h2>该数值的类型为:{{typeof age}}</h2>
<!-- trim表示去除文本框中的前后空格-->
<input type="text" v-model.trim="text">
<h2>您输入的内容为:{{text}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'hello word',
age: 0,
text: '哈哈哈'
}
})
</script>
</body>
</html>
|
import math
import numpy as np
import torch
from torch.nn import functional as F
from lkan.utils.kan import conv2d_efficient_fftkan
from .kan_linear import KANLinear
from .kan_linear_fft import KANLinearFFT
class KANConv2d(torch.nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=True,
grid_size=3,
noise_scale=0.1,
noise_scale_base=0.1,
scale_spline=1.0,
base_fun=torch.nn.SiLU(),
scale_spline_trainable=True,
scale_base_trainable=True,
chunk_size=None,
device="cpu",
):
super().__init__()
if isinstance(kernel_size, int):
self.kernel_size = (kernel_size, kernel_size)
elif isinstance(kernel_size, tuple) and len(kernel_size) == 2:
self.kernel_size = kernel_size
else:
raise ValueError(
"kernel_size must be an integer or a tuple of two integers"
)
self.in_channels = in_channels
self.out_channels = out_channels
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.grid_size = grid_size
self.base_fun = base_fun
self.device = device
self.chunk_size = chunk_size
if scale_spline is not None:
self.scale_spline = torch.nn.Parameter(
torch.full(
(
self.out_channels,
self.in_channels // self.groups,
self.kernel_size[0],
self.kernel_size[1],
),
fill_value=scale_spline,
device=device,
),
requires_grad=scale_spline_trainable,
)
else:
self.register_buffer("scale_spline", torch.tensor([1.0], device=device))
self.coeff = torch.nn.Parameter(
torch.rand(
2,
self.out_channels,
(self.in_channels // self.groups),
self.kernel_size[0],
self.kernel_size[1],
grid_size,
device=device,
)
* noise_scale
/ (np.sqrt(kernel_size**2) * np.sqrt(grid_size)),
) # [2, out_channels, kernel_size**2, grid_size]
self.scale_base = torch.nn.Parameter(
(
1 / (kernel_size**2**0.5)
+ (
torch.randn(
self.out_channels,
self.in_channels // self.groups,
self.kernel_size[0],
self.kernel_size[1],
device=device,
)
* 2
- 1
)
* noise_scale_base
),
requires_grad=scale_base_trainable,
)
if bias:
self.bias = torch.nn.Parameter(
torch.zeros(out_channels, device=device), requires_grad=True
)
else:
self.bias = bias
self.conv_fftkan = conv2d_efficient_fftkan
def forward(self, x):
x = self.conv_fftkan(
x,
self.scale_base,
self.scale_spline,
self.coeff,
self.bias,
stride=self.stride,
padding=self.padding,
dilation=self.dilation,
groups=self.groups,
)
return x
|
'use client'
import Image from "next/image";
import { Splide, SplideSlide, SplideTrack } from '@splidejs/react-splide';
import '@splidejs/react-splide/css';
import Link from "next/link";
function timeSinceCreation(createdDate) {
// Get the current date
var currentDate = new Date();
// Convert the createdDate string to a Date object
var createdDateObj = new Date(createdDate);
// Calculate the difference in milliseconds
var differenceInMs = currentDate - createdDateObj;
// Convert milliseconds to seconds
var differenceInSeconds = differenceInMs / 1000;
// Determine the appropriate time unit
if (differenceInSeconds < 60) {
return Math.floor(differenceInSeconds) + " second" + (Math.floor(differenceInSeconds) === 1 ? "" : "s") + " ago";
} else if (differenceInSeconds < 3600) {
var minutes = Math.floor(differenceInSeconds / 60);
return minutes + " minute" + (minutes === 1 ? "" : "s") + " ago";
} else if (differenceInSeconds < 86400) {
var hours = Math.floor(differenceInSeconds / 3600);
return hours + " hour" + (hours === 1 ? "" : "s") + " ago";
} else if (differenceInSeconds < 604800) {
var days = Math.floor(differenceInSeconds / 86400);
return days + " day" + (days === 1 ? "" : "s") + " ago";
} else if (differenceInSeconds < 2419200) { // Assuming 7 days as a week
var weeks = Math.floor(differenceInSeconds / 604800);
return weeks + " week" + (weeks === 1 ? "" : "s") + " ago";
} else {
return "more than a month ago";
}
}
function formatNumber(number) {
if (number >= 1000000000000) {
return (number / 1000000000000).toFixed(1) + ' T';
} else if (number >= 1000000000) {
return (number / 1000000000).toFixed(1) + ' B';
} else if (number >= 1000000) {
return (number / 1000000).toFixed(1) + ' M';
} else if (number >= 1000) {
return (number / 1000).toFixed(1) + ' K';
} else {
return number.toString();
}
}
function truncateString(str, num) {
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
export default function SlideShow({ feed }) {
return (
<Splide
options={ {
rewind: true,
autoplay: true,
gap : '1rem',
arrows: false,
} }
hasTrack={ false } aria-label="...">
<div className="custom-wrapper">
<div className="splide__progress">
<div className="splide__progress__bar" />
</div>
<SplideTrack className="h-60 md:h-[26rem] b-rad">
{feed.map((f) => (
<SplideSlide key={f.id} className="h-full relative">
<Link className="h-full absolute w-full bg-transparent" href={`/blogs/${f.id}`}></Link>
<Image src={f.images[0].url} width={1000} height={1000} alt="Image 1" className="object-cover object-top w-full h-full b-rad" />
<div className="b-rad w-full absolute bg-black/5 backdrop-blur-sm text-white bottom-0 pb-8 md:pb-8 px-2 flex justify-center">
<span className="md:hidden w-full md:w-8/12 mx-auto text-center text-base md:text-xl font-semibold">{truncateString(f.title, 70)}</span>
<span className="hidden md:block w-full md:w-8/12 mx-auto text-center text-base md:text-xl font-semibold">{f.title}</span>
</div>
</SplideSlide>
))}
</SplideTrack>
</div>
</Splide>
);
}
|
#include <stdio.h>
#include<stdlib.h>
//Prototype of structure.
struct Node
{
int data;
struct Node *link;
};
void linklistTraversal(struct Node* ptr)
{
while(ptr != NULL)
{
printf("%d-->",ptr-> data);
ptr=ptr->link;
}
printf("Null\n");
}
//Insert at the beginning
struct Node * insertAtFirst(struct Node * head,int data)
{
struct Node * ptr = (struct Node *)malloc(sizeof(struct Node));
ptr-> link = head;
ptr-> data = data;
return ptr;
}
//Insert in between
struct Node * insertAtIndex(struct Node *head,int data,int index)
{
struct Node * ptr = (struct Node *)malloc(sizeof(struct Node));
struct Node * temp = head;
int i=0;
while(i!=index-1)
{
temp = temp ->link;
i++;
}
ptr->data=data;
ptr ->link = temp->link;
temp -> link = ptr;
return head;
}
struct Node * insertAtEnd(struct Node *head,int data)
{
struct Node * ptr = (struct Node *)malloc(sizeof(struct Node));
ptr->data=data;
struct Node *temp = head;
while(temp->link != NULL)
{
temp=temp->link;
}
temp->link=ptr;
ptr->link=NULL;
return head;
}
//Deletion at first
struct Node * deleteAtFirst(struct Node* head)
{
if(head==NULL)
return 0;
else
{
struct Node * temp= head;
head = temp->link;
free(temp);
return head;
}
}
struct Node * deleteAtEnd(struct Node *head)
{
}
//Main Function
int main(int argc, char const *argv[])
{
struct Node * head;
struct Node * second;
struct Node * third;
struct Node * fourth;
head =(struct Node *)malloc(sizeof(struct Node));
second =(struct Node *)malloc(sizeof(struct Node));
third =(struct Node *)malloc(sizeof(struct Node));
fourth =(struct Node *)malloc(sizeof(struct Node));
head-> data = 7;
head-> link = second;
second-> data=8;
second->link=third;
third-> data=69;
third->link = fourth;
fourth-> data=70;
fourth->link = NULL;
printf("Linked list before insertion\n");
linklistTraversal(head);
//head = insertAtFirst(head,72);
//head = insertAtIndex(head,12,2);
//head = insertAtEnd(head,12);
//head=deleteAtFirst(head);
head=deleteAtEnd(head);
printf("\nLinked List after insertion\n");
linklistTraversal(head);
return 0;
}
|
from typing import List, Union
from datetime import datetime
from core.logger import get_logger
from constants.transports import TransportType
from data.directions import get_directions_by_transport_type_and_place_id
from data.types import AddressResponse, DirectionsResponse, PlacesNearby, Step
from utils.directions import get_datetime_from_str
logger = get_logger(__name__)
def get_directions_for_multiple_places(
origin: AddressResponse,
destinations: Union[List[PlacesNearby],List[AddressResponse]],
transport_types: List[TransportType],
departure_time_str:str=None,
arrival_time_str:str=None
):
origin_address = origin.formatted_address
logger.info("Converting time string to datetime object")
departure_time = get_datetime_from_str(departure_time_str) if departure_time_str is not None else None
arrival_time = get_datetime_from_str(arrival_time_str) if arrival_time_str is not None else None
directions = list(
map(
lambda destination : _get_directions_for_place(
origin_address,
destination,
transport_types,
departure_time,
arrival_time
),
destinations
)
)
return directions
def _get_directions_for_place(
origin_address: str,
destination: Union[PlacesNearby, AddressResponse],
transport_types: List[TransportType],
departure_time:datetime=None,
arrival_time:datetime=None
):
destination_name : str = destination.name
logger.info(f"Getting directions by transport types: {[transport.value for transport in transport_types]}")
direction_by_transport_type : list[dict[TransportType, DirectionsResponse]] = list(
map(
lambda transport_type : _get_directions_for_place_by_transport(
origin_address,
destination.place_id,
transport_type,
departure_time,
arrival_time
),
transport_types
)
)
return {destination_name: direction_by_transport_type}
def _get_transit_detail_from_step(
step: Step
):
additional_data = {}
if step.transport_type == TransportType.Transit and step.transit_details is not None:
logger.info("Getting additional step data for transit transport type")
transit_details = step.transit_details
additional_data.update({
"additional_data": {
"departure_stop": transit_details.departure_stop,
"arrival_stop": transit_details.arrival_stop,
"vehicle" : transit_details.line.vehicle,
"vehicle_name": transit_details.line.name,
"vehicle_short_name": transit_details.line.short_name,
"headsign": transit_details.headsign,
"num_stops": transit_details.num_stops
}
})
return {
step.transport_type: {
"distance": {
"value": step.distance_in_m,
"text": step.distance_in_text
},
"duration": {
"value": step.duration_in_s,
"text": step.duration_in_text
},
**additional_data
}
}
def _get_directions_for_place_by_transport(
origin_address: str,
destination_id: str,
transport_type: TransportType,
departure_time:datetime=None,
arrival_time:datetime=None
) -> DirectionsResponse:
additional_details = {}
logger.info(f"Getting directions to [destination_id: {destination_id}] using transport type '{transport_type.value}'")
directions : DirectionsResponse = get_directions_by_transport_type_and_place_id(
origin=origin_address,
destination_id=destination_id,
transport_type=transport_type,
departure_time=departure_time,
arrival_time=arrival_time
)
if transport_type == TransportType.Transit:
# NOTE: Only need the steps for transit mode
step_details = list(
map(
lambda step : _get_transit_detail_from_step(step),
directions.steps
)
)
additional_details.update({
"additional_details": step_details
})
return {
transport_type: {
"distance" : {
"text": directions.distance_in_text,
"value": directions.distance_in_m
},
"duration": {
"text": directions.duration_in_text,
"value": directions.duration_in_s
},
**additional_details
}
}
|
import { Command, flags } from "@oclif/command";
import { Browser, Page } from "puppeteer-core";
import cli from "cli-ux";
import { config } from "dotenv";
import { environmentVariablesFile, alert, beginScrape, downloadInstagramFile, ScrapePayload } from "../shared";
declare global {
interface Window {
_sharedData: any,
__additionalData: any,
}
}
export default class Instagram extends Command {
static description = "Command for scraping Instagram post files.";
static args = [{name: "post", required: true}];
static flags = {headless: flags.boolean({char: "h", description: "Toggle for background scraping."})};
async run() {
config({path: environmentVariablesFile});
const {INSTAGRAM} = process.env;
if (INSTAGRAM! !== "true") {
alert("You are not authenticated.", "danger");
} else if (JSON.parse(INSTAGRAM!)) {
try {
const { args, flags } = this.parse(Instagram);
if (args.post !== undefined && args.post !== null) {
const now = Date.now();
cli.action.start("Opening browser");
const { browser, page } = (await beginScrape(flags.headless))!;
cli.action.stop();
cli.action.start("Searching for files");
const payload = await detectFiles(browser, page, args.post);
cli.action.stop();
alert(`Scrape time: ${(Date.now() - now)/1000}s`, "info");
if (payload) {
const { urls, username } = payload;
for (var i = 0; i < urls.length; i += 1) {
const url = urls[i];
cli.action.start("Downloading");
if (url.includes(".jpg")) await downloadInstagramFile(url, username, ".jpg", i +1);
if (url.includes(".mp4")) await downloadInstagramFile(url, username, ".mp4", i +1);
cli.action.stop();
}
}
await browser.close();
} else return alert("Please provide a POST argument!", "danger");
} catch (error) { alert(error.message, "danger"); }
}
}
}
/**
* Scrapes Instagram post files
* @param browser Puppeteer browser
* @param page Puppeteer page
* @param id post ID
* @returns URL string array
*/
export async function detectFiles(browser: Browser, page: Page, id: string): Promise<ScrapePayload | undefined> {
try {
await page.goto(`https://www.instagram.com/p/${id}`, {waitUntil: "domcontentloaded"});
if ((await page.$("div.error-container")) !== null) {
alert(`Failed to find post ${id}`, "danger");
await browser.close();
}
const data = (await page.evaluate(() => window.__additionalData))[`/p/${id}/`].data.graphql.shortcode_media;
const username = data.owner.username;
var urls: string[] = [];
if (data.edge_sidecar_to_children) {
for (let edge of data.edge_sidecar_to_children.edges) {
if (!edge.node.is_video) urls.push(edge.node.display_url);
if (edge.node.is_video) urls.push(edge.node.video_url);
}
} else {
if (!data.is_video) urls.push(data.display_url);
if (data.is_video) urls.push(data.video_url);
}
return { urls, username };
} catch (error) { alert(error.message, "danger"); }
}
|
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC1271.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "./Bytecode.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IERC6551Account.sol";
contract ExampleERC6551Account is IERC165, IERC1271, IERC6551Account {
receive() external payable {}
function executeCall(
address to,
uint256 value,
bytes calldata data
) external payable returns (bytes memory result) {
require(tx.origin == owner(), "Not token owner");
bool success;
(success, result) = to.call{value: value}(data);
if (!success) {
assembly {
revert(add(result, 32), mload(result))
}
}
}
function token()
external
view
returns (
uint256 chainId,
address tokenContract,
uint256 tokenId
)
{
uint256 length = address(this).code.length;
return
abi.decode(
Bytecode.codeAt(address(this), length - 0x60, length),
(uint256, address, uint256)
);
}
function executeCallTransferToken(
address _to,
address _tokenAddr,
uint256 _amount
) external returns (bool) {
require(msg.sender == owner(), "not owner");
bool success;
success = IERC20(_tokenAddr).transfer(_to, _amount);
if (!success) {
return false;
}
return true;
}
function owner() public view returns (address) {
(uint256 chainId, address tokenContract, uint256 tokenId) = this
.token();
if (chainId != block.chainid) return address(0);
return IERC721(tokenContract).ownerOf(tokenId);
}
function supportsInterface(bytes4 interfaceId) public pure returns (bool) {
return (interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IERC6551Account).interfaceId);
}
function isValidSignature(bytes32 hash, bytes memory signature)
external
view
returns (bytes4 magicValue)
{
bool isValid = SignatureChecker.isValidSignatureNow(
owner(),
hash,
signature
);
if (isValid) {
return IERC1271.isValidSignature.selector;
}
return "";
}
}
|
import 'package:flutter/material.dart';
import 'package:iqra/core/utils/routes.dart';
import 'package:iqra/presentation/home/tabs/quran/sura_model.dart';
class SuraWidget extends StatelessWidget {
String suraName;
String versesNumber;
int index; //need to know user selected sura
SuraWidget(
{super.key,
required this.suraName,
required this.versesNumber,
required this.index});
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Navigator.pushNamed(context, Routes.suraDetailsScreen,
arguments: SuraModel(suraName: suraName, index: index));
},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
versesNumber,
style: Theme.of(context).textTheme.titleMedium,
textAlign: TextAlign.center,
),
Text(
suraName,
style: Theme.of(context).textTheme.titleMedium,
textAlign: TextAlign.center,
),
],
),
);
}
}
|
<?php
class Site extends CI_Model{
function __construct(){
parent::__construct();
$this->load->database();
$this->load->library('session');
}
function show_index(){
$this->check_session();
$query = "select pro_id, pro_name, photo from product where category = 'brownie';";
$result = $this->db->query($query);
$result = $result->result_array();
$data['brownies'] = $result;
$query = "select pro_id, pro_name, photo from product where category = 'macaroon';";
$result = $this->db->query($query);
$result = $result->result_array();
$data['macaroons'] = $result;
$query = "select pro_id, pro_name, photo from product where category = 'chocolate';";
$result = $this->db->query($query);
$result = $result->result_array();
$data['chocolates'] = $result;
$query = "select pro_id, pro_name, photo from product where category = 'liquorice';";
$result = $this->db->query($query);
$result = $result->result_array();
$data['liquorice'] = $result;
$query = "select pro_id, pro_name, photo from product where category = 'pastry';";
$result = $this->db->query($query);
$result = $result->result_array();
$data['pastries'] = $result;
$query = "select pro_id, pro_name, photo from product where category = 'cake';";
$result = $this->db->query($query);
$result = $result->result_array();
$data['cakes'] = $result;
$query = "select pro_id, pro_name, photo from product where category = 'biscuit';";
$result = $this->db->query($query);
$result = $result->result_array();
$data['biscuits'] = $result;
$this->load->view('viewer/index', $data);
}
function show_login_register($sign_in_error = '', $sign_up_error = ''){
$this->check_session();
$data['sign_in_error'] = $sign_in_error;
$data['sign_up_error'] = $sign_up_error;
$this->load->view('viewer/login_register', $data);
}
function category($c){
$this->check_session();
$query = "select pro_id, pro_name, photo from product where category = '{$c}';";
$result = $this->db->query($query);
$result = $result->result_array();
$data['category'] = $result;
$c = ucfirst($c).'s';
$data['header'] = $c;
$this->load->view('viewer/category', $data);
}
function product($p){
$this->check_session();
$query = "select * from product where pro_id = '{$p}';";
$result = $this->db->query($query);
$result = $result->row_array();
$data['product'] = $result;
$this->load->view('viewer/product', $data);
}
function sign_in(){
$this->load->library('form_validation');
$config = array(
array(
'field' => 'sign_in_username',
'label' => 'Username',
'rules' => 'required|callback_username_exists'
),
array(
'field' => 'sign_in_password',
'label' => 'Password',
'rules' => 'required|callback_validate_password'
)
);
$this->form_validation->set_rules($config);
if($this->form_validation->run()){
$query = "select cus_id from customer where username = '{$this->input->post('sign_in_username')}' and password = '{$this->input->post('sign_in_password')}';";
$result = $this->db->query($query);
$result = $result->row_array();
$this->show_user($result['cus_id']);
}
else{
$error = validation_errors();
$this->show_login_register($error, '');
}
}
function sign_up(){
$this->load->library('form_validation');
$config = array(
array(
'field' => 'sign_up_username',
'label' => 'Username',
'rules' => 'required|is_unique[customer.username]'
),
array(
'field' => 'sign_up_password',
'label' => 'Password',
'rules' => 'required|min_length[6]'
),
array(
'field' => 'sign_up_confirm_password',
'label' => 'Confirm Password',
'rules' => 'required|matches[sign_up_password]'
),
array(
'field' => 'sign_up_first_name',
'label' => 'First Name',
'rules' => 'required|alpha'
),
array(
'field' => 'sign_up_last_name',
'label' => 'Last Name',
'rules' => 'required|alpha'
),
array(
'field' => 'sign_up_address',
'label' => 'Address',
'rules' => 'required'
),
array(
'field' => 'sign_up_phone',
'label' => 'Phone',
'rules' => 'required'
),
array(
'field' => 'sign_up_email',
'label' => 'Email',
'rules' => 'required|valid_email|is_unique[customer.email]'
)
);
$this->form_validation->set_rules($config);
if($this->form_validation->run()){
$query = "insert into customer(username, password, cus_name, address, phone, email) values('{$this->input->post('sign_up_username')}', '{$this->input->post('sign_up_password')}', '{$this->input->post('sign_up_first_name')} {$this->input->post('sign_up_last_name')}', '{$this->input->post('sign_up_address')}', '{$this->input->post('sign_up_phone')}', '{$this->input->post('sign_up_email')}');";
$this->db->query($query);
$query = "select cus_id from customer where username = '{$this->input->post('sign_up_username')}' and password = '{$this->input->post('sign_up_password')}';";
$result = $this->db->query($query);
$result = $result->row_array();
$this->show_user($result['cus_id']);
}
else{
$error = validation_errors();
$this->show_login_register('', $error);
}
}
function search(){
$query = "select pro_id, pro_name from product where pro_name like '%{$this->input->post('search')}%';";
$result = $this->db->query($query);
$result = $result->result_array();
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
}
function check_session(){
if($this->session->userdata('logged_in')){
redirect("./user");
}
}
function show_user($id){
$newdata = array(
'id' => $id,
'logged_in' => true,
'shopping_cart' => array()
);
$this->session->set_userdata($newdata);
redirect("./user");
}
}
?>
|
package com.example.server.jwt;
import com.example.server.security.SecurityUser;
import com.example.server.token.Token;
import com.example.server.token.TokenRepository;
import com.example.server.user.User;
import com.example.server.user.UserService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@AllArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtUtil jwtUtil;
private final UserService userService;
private final TokenRepository tokenRepository;
@Override
protected void doFilterInternal(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain
) throws ServletException, IOException {
String token = getJWTFromRequest(request);
String username = null;
if(StringUtils.hasText(token)){
username = jwtUtil.getUsernameFromToken(token);
} else {
filterChain.doFilter(request, response);
return;
}
if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){
//get user by username from the database
User user = userService.findUserByUserName(username);
var isTokenValid = tokenRepository.findByToken(token)
.map(t -> !t.isExpired() && !t.isRevoked())
.orElse(false);
if(user != null && isTokenValid && jwtUtil.isTokenValid(token, user.getUsername())){
SecurityUser securityUser = new SecurityUser(user);
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(
securityUser,
null,
securityUser.getAuthorities()
);
authToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response); // pass to the next filter
}
private String getJWTFromRequest(HttpServletRequest request){
String bearerToken = request.getHeader("Authorization");
if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){
return bearerToken.substring(7);
}
return null;
}
}
|
Feature: Create bank account
Background: Login
Given A user open signin page
When User successfully logged in
|username|password |
|KhanhOng|Khanh@123|
And A User click bank account
Scenario: Create bank account
When A user click icon add bank account
Then Verify Create bank account form should be display
When A user enter bank name 'The Best Bank'
When A user enter routing number '987654321'
When A use enter account number '123456789'
When A user click save button to add bank account
Then Verify new bank account 'The Best Bank' is create
Scenario: Display bank account form errors
When A user click icon add bank account
Then Verify Create bank account form should be display
When A user enter bank name 'The' and clear it
Then Verify error message bankname 'Enter a bank name' should be display
When A user enter bank name 'The'
Then Verify error message bankname 'Must contain at least 5 characters' should be display
When A user enter routing number and clear it
Then Verify error message routingnumber 'Enter a valid bank routing number' should be display
When A user enter routing number '12345678'
Then Verify error message routingnumber 'Must contain a valid routing number' should be display
When A user enter routing number '123456789'
Then Then Verify no exit routingnumber
When A use enter account number and clear it
Then Verify error message accountnumber 'Enter a valid bank account number' should be display
When A use enter account number '12345678'
Then Verify error message accountnumber 'Must contain at least 9 digits' should be display
When A use enter account number '123456789'
Then Verify no exit accountnumber
When A use enter account number '12345678911'
Then Verify no exit accountnumber
When A use enter account number '1234567891111'
Then Verify error message accountnumber 'Must contain no more than 12 digits' should be display
Then Verify save button to add bank account is disabled
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->
<title>WebSocket chat example</title>
<!-- BOOTSTRAP CORE STYLE CSS -->
<link href="assets/css/bootstrap.css" rel="stylesheet" />
<script type="text/javascript">
var ws;
function WebSocketTest() {
if ("WebSocket" in window) {
// Let us open a web socket
ws = new WebSocket("ws://127.0.0.1:2222/");
ws.onerror = function(evt) {
alert("Error" + evt.data);
};
ws.onopen = function() {
alert("You can start talking to other connected people...");
};
ws.onmessage = function(evt) {
var received_msg = evt.data;
// This is ugly, but it is only for demo purposes
document.getElementById('messages').innerHTML = '<li class="media"><div class="media-body"><div class="media"><div class="media-body">' + received_msg + '<hr /> </div></div></div></li>' + document.getElementById('messages').innerHTML;
};
ws.onclose = function(event) {
var reason;
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if (event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if (event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if (event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if (event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if (event.code == 1005)
reason = "No status code was actually present.";
else if (event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if (event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if (event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if (event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if (event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if (event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if (event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
alert("Connection was closed with close code " + event.code + " with given reason: " + reason);
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
function sendMSG() {
if (document.getElementById("txt").value) {
ws.send(document.getElementById("txt").value);
document.getElementById("txt").value = "";
}
}
function closeConnection() {
ws.close();
}
</script>
</head>
<body style="font-family:Verdana">
<div class="container">
<div class="row " style="padding-top:40px;">
<h3 class="text-center">WebSocket chat example </h3>
<br />
<br />
<div class="col-md-8">
<input type="text" size="40" placeholder="Press enter to send message" id="txt" width="50px" onkeyup="if (event.keyCode == 13)
document.getElementById('idd').click()" />
<input onclick="javascript:WebSocketTest()" value="Join chat" type="button" class="btn btn-primary"/>
<input id="idd" onclick="javascript:sendMSG()" value="Send message" type="button" class="btn btn-default"/>
<input type="button" id="idClose" onclick="javascript:closeConnection()" value="Close connection" class="btn btn-default" />
<br />
<br />
<div class="panel panel-info">
<div class="panel-body">
<ul class="media-list" id="messages">
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
|
/*
Copyright (c) 2015, Digi International Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*******************************************************************************
bsd.c
A demonstration of several advanced TCP/IP functions, that are used
for namespace (DNS) issues, and finding out information about the
remote host.
*******************************************************************************/
/*********************************************************
* Example of the use of various naming functions
*
* To use:
* Set the IP address / netmask above.
* Set the domainname / hostname above.
* Run, and when it prints your domain name,
* telnet to it from another host
* You should see information about the connection
* be printed out.
**********************************************************/
#class auto
/*
* NETWORK CONFIGURATION
* Please see the function help (Ctrl-H) on TCPCONFIG for instructions on
* compile-time network configuration.
*/
#define TCPCONFIG 1
/*
* Place to listen for incoming request. 23 is TELNET port.
*/
#define MY_TEST_PORT 23
/*
* Domain name configuration
*
* This sets your hostname and domainname. If your computer has an
* internet address like: "test.digi.com", your hostname
* is "test", and your domainname is "digi.com".
*/
#define MY_HOST "test"
#define MY_DOMAIN "digi.com"
/********************************
* End of configuration section *
********************************/
#memmap xmem
#use "dcrtcp.lib"
tcp_Socket tcpsock;
tcp_Socket *const s = &tcpsock;
void main()
{
char ipbuf[16];
int status;
struct sockaddr sock_addr;
sock_init_or_exit(1);
sethostname(MY_HOST);
setdomainname(MY_DOMAIN);
printf("We are %s.%s\n", gethostname(NULL, 0), getdomainname(NULL, 0));
printf("Telnet to port %u.\n", MY_TEST_PORT);
tcp_listen((tcp_Socket*)s,MY_TEST_PORT,0,0,NULL,0);
while( ! tcp_established( (tcp_Socket *)s ) ) {
if( ! tcp_tick( (sock_type *) s ) ) {
printf( "ERROR: listening\n" );
exit( 99 );
}
}
printf("Receiving incoming connection\npsocket(s) -> ");
psocket((sock_type *)s);
printf("\n\n");
if(0 == getpeername((sock_type *)s, &sock_addr, NULL)) {
printf("getpeername: %s:%u",
inet_ntoa(ipbuf, sock_addr.s_ip),
sock_addr.s_port
);
} else {
printf("getpeername() retuned no data!\n");
}
printf("\n");
if(0 == getsockname((sock_type *)s, &sock_addr, NULL)) {
printf("getmyname: %s:%u",
inet_ntoa(ipbuf, sock_addr.s_ip),
sock_addr.s_port
);
} else {
printf("getsockname() retuned no data!\n");
}
printf("\n\nClosing socket...\n");
sock_close(s);
// Discard any data until fully closed.
while(tcp_tick(s)) sock_fastread(s, NULL, 1024);
printf("Socket closed. All done!\n");
}
|
#include "main.h"
/**
* _strlen - calculate the length of a string
* @s: String of character to counted
*
* Return: the length of the string
*/
int _strlen(char *s)
{
int k;
k = 0;
while (s[k] != '\0')
{
k++;
}
return (k);
}
|
//
// Created by Jason on 5/9/2017.
//
#include <string>
#include <iostream>
#include <iomanip>
#include "logging.h"
#ifndef KRUSKAL_DEBUGUTILS_H
#define KRUSKAL_DEBUGUTILS_H
using std::cout;
using std::endl;
using std::flush;
using std::setw;
using std::setprecision;
using std::string;
using std::to_string;
/// Print an array to DEBUG log level.
///
/// \tparam T The element type in the array
/// \param tag The tag of this line of log.
/// \param list The array
/// \param size the length of the array
template<typename T>
void debugPrintArray(string tag, T *list, int size);
/// Print a matrix (2d array) to DEBUG log level
///
/// \tparam T The element type in the matrix
/// \param matrix The matrix
/// \param tag The tag of this line of log.
/// \param matrixSize the size of the matrix.
template<typename T>
void debugPrintMatrix(string tag, T **matrix, int matrixSize);
/// Print an array to DEBUG log level.
///
/// \tparam T The element type in the array
/// \param tag The tag of this line of log.
/// \param list The array
/// \param size the length of the array
template<typename T>
void debugPrintArray(string tag, T *list, int size) {
if (level <= DEBUG) {
cout << getFormattedTime() << " - ";
cout << setw(5) << "DEBUG" << " - ";
printTag(tag);
string msg = "Print array ===> ";
if (list == nullptr || size < 1)
msg += "NULL";
else {
cout << endl << flush;
cout << getFormattedTime() << " - ";
cout << setw(5) << "DEBUG" << " - ";
printTag(tag);
msg += "[";
for (int i = 0; i < size; ++i)
msg += to_string(list[i]) + ",";
msg = msg.substr(0, msg.length() - 1) + "]";
}
cout << msg << endl << flush;
}
}
/// Print a matrix (2d array) to DEBUG log level
///
/// \tparam T The element type in the matrix
/// \param matrix The matrix
/// \param tag The tag of this line of log.
/// \param matrixSize the size of the matrix.
template<typename T>
void debugPrintMatrix(string tag, T **matrix, int matrixSize) {
if (level <= DEBUG) {
cout << getFormattedTime() << " - ";
cout << setw(5) << "DEBUG" << " - ";
printTag(tag);
cout << "Print Matrix ===>" << endl << flush;
if (matrix == nullptr || matrixSize < 1) {
printTag(tag);
cout << "The given matrix is NULL." << endl << flush;
return;
}
for (int i = 0; i < matrixSize; ++i)
debugPrintArray<T>(tag, matrix[i], matrixSize);
}
}
#endif //KRUSKAL_DEBUGUTILS_H
|
import tkinter
from tkinter.messagebox import showinfo as alert
from tkinter.messagebox import askyesno as question
from tkinter.simpledialog import askstring as prompt
import customtkinter
'''
Enunciado:
2. El departamento de Construcción Rural requiere una herramienta que facilite el calculo de materiales necesarios
a la hora de realizar un alambrado permetral, se le solicita al usuario que ingrese el ancho y el largo del terreno.
A. Informar los metros cuadrados del terreno y los metros lineales del perimetro
B. Informar la cantidad de postes de quebracho Grueso de 2.4 mts (van cada 250 mts lineales y en las esquinas).
C. Informar la cantidad de postes de quebracho Fino de 2.2 mts (van cada 12 mts lineales, si en es lugar no se encuentra el poste grueso).
D. Informar la cantidad de varillas (van cada 2 mts lineales).
E. Informar la cantidad de alambre alta resistencia 17/15 considerando 7 hilos.
EJ 36 MTS X 24 MTS
(G)Poste Quebracho Grueso de 2.4 mts
(V)Poste Quebracho Fino de 2.2 mts
(F)Varillas
G V V V V V F V V V V V F V V V V V G
V V
V V
V V
V V
V V
F F
V V
V V
V V
V V
V V
G V V V V V F V V V V V F V V V V V G
'''
class App(customtkinter.CTk):
def __init__(self):
super().__init__()
# configure window
self.title("UTN FRA")
self.label_1 = customtkinter.CTkLabel(master=self, text="Largo")
self.label_1.grid(row=0, column=0, padx=20, pady=10)
self.txt_largo = customtkinter.CTkEntry(master=self)
self.txt_largo.grid(row=0, column=1)
self.label_2 = customtkinter.CTkLabel(master=self, text="Ancho")
self.label_2.grid(row=1, column=0, padx=20, pady=10)
self.txt_ancho = customtkinter.CTkEntry(master=self)
self.txt_ancho.grid(row=1, column=1)
self.btn_calcular = customtkinter.CTkButton(
master=self, text="CALCULAR", command=self.btn_calcular_on_click)
self.btn_calcular.grid(row=3, pady=10, columnspan=2, sticky="nsew")
def btn_calcular_on_click(self):
largo = self.txt_largo.get()
largo = int(largo)
ancho = self.txt_ancho.get()
ancho = int(ancho)
metros2 = largo*ancho
perimetro = largo*2 + ancho*2
metroslineales = perimetro
cantidad_quebrachogrueso = 4 + metroslineales / 250
cantidad_quebrachofino = metroslineales / 12
cantidad_de_varillas = metroslineales /2
alambre = metroslineales * 7
alert("Calculo.", f"El terreno tiene {int(metros2)} metros cuadrados\n{int(metroslineales)} Metros lineales \nSe utilizaran {int(cantidad_quebrachogrueso)} Quebrachos gruesos \n{int(cantidad_quebrachofino)} Quebrachos finos \n {int(cantidad_de_varillas)} Varillas\n{int(alambre)} Alambres de alta resistencia")
if __name__ == "__main__":
app = App()
app.geometry("300x300")
app.mainloop()
|
/*******************************************************************************
* Copyright (c) 2024. @author: Breno Vambaster
******************************************************************************/
package models;
import entidades.Reserva;
import entidades.Sala;
import helpers.HelperUtil;
import interfaces.IMetodos;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import helpers.ReservaHelper;
public class ReservaModel implements IMetodos<Reserva> {
private static ArrayList<Reserva> reservasList = new ArrayList<>();
private static Integer id = 0;
/**
* @param reserva
* @return
*/
@Override
public Integer create(Reserva reserva) {
HelperUtil.validateObject(reserva);
if (ReservaHelper.ConflitaHorario(this.reservasList, reserva))
throw new RuntimeException("Conflito de horário!");
reserva.setId(id);
reservasList.add(reserva);
return id++;
}
/**
* @param reserva
*/
@Override
public void remove(Reserva reserva) {
HelperUtil.validateObject(reserva);
reservasList.removeIf(r -> r.getId().equals(reserva.getId()));
}
/**
* @param reserva
*/
@Override
public Boolean update(Reserva reserva) {
HelperUtil.validateObject(reserva);
for (Reserva r : reservasList) {
if (r.getId().equals(reserva.getId())) {
r.setEquipamentos(reserva.getEquipamentos());
r.setSala(reserva.getSala());
r.setUsuario(reserva.getUsuario());
r.setUsuario(reserva.getUsuario());
r.setTipo(reserva.getTipo());
r.setDataAlocacao(reserva.getDataAlocacao());
r.setHoraInicio(reserva.getHoraInicio());
r.setHoraFim(reserva.getHoraFim());
r.setAssunto(reserva.getAssunto());
r.setAtivo(reserva.isAtivo());
return true;
}
}
return false;
}
/**
* @param id
* @return
*/
@Override
public Reserva get(int id) {
return reservasList.stream().filter(r -> r.getId().equals(id)).findFirst().orElse(null);
}
/**
* A partir de uma data, hora de início e hora de fim, verifica quais salas estão disponíveis
* para uma reserva. Retorna uma lista vazia ou não.
*
* @param horaInicio - Hora de início da reserva (Exemplo: 10:00)
* @param horaFim - Hora de fim da reserva (Exemplo: 12:00)
* @param dataAlocacao - Data da reserva (Exemplo: 2024-12-12)
* @return ArrayList<Sala> - Lista de salas disponíveis
*/
public ArrayList<Sala> obterSalasLivres(LocalTime horaInicio, LocalTime horaFim, LocalDate dataAlocacao) {
// copia da lista de reservas
ArrayList<Reserva> reservas = this.getAll();
ArrayList<Sala> salasOcupadas = new ArrayList<>();
// copia da lista de salas
SalaModel salaModel = new SalaModel();
ArrayList<Sala> salasPersistidas = salaModel.getAll();
for (Reserva r : reservas) {
if (r.getDataAlocacao().equals(dataAlocacao) && HelperUtil.isHorarioConflitante(r, horaInicio, horaFim)) {
salasOcupadas.add(r.getSala());
}
}
salasPersistidas.removeAll(salasOcupadas);
return salasPersistidas;
}
/**
* A partir de uma data, hora de início e hora de fim, verifica quais salas estão reservadas
*
* @param horaInicio
* @param horaFim
* @param dataAlocacao
* @return ArrayList<Sala> - Lista de salas reservadas
*/
public ArrayList<Sala> obterSalasReservadas(LocalTime horaInicio, LocalTime horaFim, LocalDate dataAlocacao) {
// copia da lista de reservas
ArrayList<Reserva> reservas = this.getAll();
ArrayList<Sala> salasReservadas = new ArrayList<>();
for (Reserva r : reservas) {
if (r.getDataAlocacao().equals(dataAlocacao) && HelperUtil.isHorarioConflitante(r, horaInicio, horaFim)) {
salasReservadas.add(r.getSala());
}
}
return salasReservadas;
}
public ArrayList<Sala> obterSalasReservadasPorDia(LocalDate dataAlocacao) {
ArrayList<Reserva> reservas = this.getAll();
ArrayList<Sala> salasReservadas = new ArrayList<>();
for (Reserva r : reservas) {
if (r.getDataAlocacao().equals(dataAlocacao)) {
salasReservadas.add(r.getSala());
}
}
return salasReservadas;
}
public ArrayList<Sala> obterSalasReservadasPorMes(LocalDate dataAlocacao) {
ArrayList<Reserva> reservas = this.getAll();
ArrayList<Sala> salasReservadas = new ArrayList<>();
for (Reserva r : reservas) {
if (r.getDataAlocacao().getMonth().equals(dataAlocacao.getMonth())) {
salasReservadas.add(r.getSala());
}
}
return salasReservadas;
}
/**
* @return
*/
@Override
public ArrayList<Reserva> getAll() {
return reservasList;
}
}
|
#include <iostream>
#include "Array.hpp"
#define MAX_VAL 750
int main(int, char**)
{
Array<int> numbers(MAX_VAL);
int* mirror = new int[MAX_VAL];
srand(time(NULL));
for (int i = 0; i < MAX_VAL; i++)
{
const int value = rand();
numbers[i] = value;
mirror[i] = value;
}
//mine
for (int i = 0; i < 5; i++)
{
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
for (int i = 0; i < 5; i++)
{
std::cout << mirror[i] << " ";
}
std::cout << std::endl;
//SCOPE
{
Array<int> tmp = numbers;
Array<int> test(tmp);
//mine
for (int i = 0; i < 5; i++)
{
std::cout << test[i] << " ";
}
std::cout << std::endl;
//Const Test
const Array<int> test2(tmp);
test[0] = 4;
// test2[0] = 5;
for (int i = 0; i < 5; i++)
{
std::cout << test[i] << " ";
}
std::cout << std::endl;
//=Test
test = test2;
for (int i = 0; i < 5; i++)
{
std::cout << test[i] << " ";
}
std::cout << std::endl;
}
for (int i = 0; i < MAX_VAL; i++)
{
if (mirror[i] != numbers[i])
{
std::cerr << "didn't save the same value!!" << std::endl;
return 1;
}
}
try
{
numbers[-2] = 0;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
try
{
numbers[MAX_VAL] = 0;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
for (int i = 0; i < MAX_VAL; i++)
{
numbers[i] = rand();
}
delete [] mirror;
//mine
if (numbers.size() == MAX_VAL)
{
std::cout << "size() is ok!" << std::endl;
}
//system("leaks array");
return 0;
}
|
// Упражнение 15.15. Определите собственные версии классов Disc_quote и
// Bulk_quote.
#include <iostream>
#include <string>
class Quote {
public:
Quote() = default;
Quote(const std::string &book, double sales_price)
: bookNo(book), price(sales_price) {}
std::string isbn() const { return bookNo; }
virtual double net_price(std::size_t n) const { return n * price; }
virtual ~Quote() = default;
private:
std::string bookNo;
protected:
double price = 0.0;
};
class Disc_quote : public Quote {
public:
Disc_quote() = default;
Disc_quote(const std::string &book, double p, std::size_t qty, double disc)
: Quote(book, p), quantity(qty), discount(disc) {}
double net_price(std::size_t cnt) const = 0;
protected:
std::size_t quantity = 0;
double discount = 0.0;
};
class Bulk_quote : public Disc_quote {
public:
Bulk_quote() = default;
Bulk_quote(const std::string &book, double p, std::size_t qty, double disc)
: Disc_quote(book, p, qty, disc) {}
double net_price(std::size_t cnt) const override {
if (cnt >= quantity)
return cnt * (1 - discount) * price;
else
return cnt * price;
}
};
/* class Bulk_quote : public Disc_quote {
public:
Bulk_quote() = default;
Bulk_quote(const std::string &book, double p, std::size_t qty, double disc)
: Disc_quote(book, p, qty, disc) {}
double net_price(std::size_t cnt) const override {
if (cnt < quantity) // Достаточно поменять условие.
return cnt * (1 - discount) * price;
else
return cnt * price;
}
}; */
|
# Global Economic Dashboard
<table>
<tr>
<td><img src="./Global%20Economic%20Dashboard/www/Global%20Economic%20Dashboard%20(2).png" alt="Global Economic Dashboard Data Tab"></td>
<td><img src="./Global%20Economic%20Dashboard/www/Global%20Economic%20Dashboard.png" alt="Global Economic Dashboard Future Trends Tab"></td>
</tr>
</table>
## Overview
Welcome to the Global Economic Dashboard, a data analytics and visualization Shiny app designed to provide insights into key economic indicators for 20 countries. This interactive tool spans the years 2012 to 2022 and incorporates a Regression Machine Learning model to predict Education Expenditure (%GDP). Explore diverse data through 2D and 3D charts, offering a comprehensive view of economic trends.
## Features
### Data Tab
- Checkbox: Show row names in the data table.
- Data table displaying economic indicators for the selected countries.
### Visualization Tab
- Select a country and an economic indicator to visualize trends from 2012 to 2022 using an interactive line plot.
### 3D Visualization Tab
- Choose between scatterplot3d or rgl for 3D visualization.
- Select an indicator and a year to explore economic landscapes in three dimensions.
### Future Trends Tab
- Input numeric values for future trends in export, health expenditure, import, industry, and inflation rate.
- Click "Predict" to use the Regression Machine Learning model for predicting future trends in Education Expenditure (%GDP).
- View the model's prediction in the "Regression Model Results" section.
## How to Use
1. Navigate through the tabs to explore different aspects of the economic data.
2. In the "Visualization" tab, select a country and an economic indicator to view historical trends.
3. Use the 3D Visualization tab to explore economic indicators in a three-dimensional space.
4. In the "Future Trends" tab, input numeric values and click "Predict" to get future trend predictions for Education Expenditure (%GDP).
## Notes
- This app covers 20 countries, including Argentina, Australia, Brazil, Canada, China, France, Germany, India, Indonesia, Italy, Japan, Korea, Mexico, Saudi Arabia, South Africa, Turkey, United Arab Emirates, United Kingdom, and the United States.
- The Regression Machine Learning model is utilized for predicting Education Expenditure (%GDP) based on the input parameters.
## Getting Started
1. Open the app by running `shiny::runApp("app_directory_path")` in RStudio.
2. Ensure you have the required packages installed using `install.packages(c("shiny", "leaflet", "DT", "scatterplot3d", "rgl", "tidyverse", "randomForest"))`.
## PowerBI Report

Check out the [PowerBI report](https://github.com/simran08udhani/RLabBasedProject/blob/main/R%20project%20Report.pbix) for visualizations and insights complementing the Shiny app.
## Credits
This app was developed using the Shiny framework and various R packages. Data is sourced from the World Bank, and the Regression Machine Learning model is built using the "ML_education_expenditure_model.R" script.
## Author
Simran Udhani
## License
The Global Economic Dashboard is licensed under the [MIT License](LICENSE).
---
Feel free to contribute, report issues, or suggest improvements!
|
package transaction.test.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import transaction.test.entity.Expense;
import transaction.test.service.TransactionService;
@WebMvcTest(TransactionController.class)
class TransactionControllerTest {
@MockBean
private TransactionService transactionService;
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper mapper;
@Test
void setExpense() throws Exception {
Expense testExpense = Expense.builder()
.accountFrom(1000000000)
.accountTo(1000000000)
.currencyShortname("USD")
.sum(BigDecimal.valueOf(500))
.expenseCategory("product")
.build();
String testExpenseJson = mapper.writeValueAsString(testExpense);
mockMvc.perform(
post("/transactions/expense/add")
.contentType(MediaType.APPLICATION_JSON)
.content(testExpenseJson))
.andExpect(status().isOk());
}
@Test
void setExchengeRate() throws Exception {
mockMvc.perform(
post("/transactions/exchenge-rate"))
.andExpect(status().isOk());
}
}
|
# frozen_string_literal: true
class ServiceInquiry < ApplicationRecord
belongs_to :job_posting
validates :name, :email, :service_beginning, :service_duration, :message, presence: true
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
attr_accessor :skip_inquiry_mail
attr_reader :agreement
attribute :agreement, :boolean, default: false
after_create_commit :send_inquiry_mails
def agreement=(value)
@agreement = ['1', true].include?(value)
end
private
def send_inquiry_mails
return if skip_inquiry_mail == true
ServiceInquiryMailer.with(service_inquiry_id: id).send_inquiry.deliver_later
ServiceInquiryMailer.with(service_inquiry_id: id).send_confirmation.deliver_later
end
end
|
import React, { useState } from 'react';
import search from '../../../assets/icons/search.svg';
import './Search.scss';
const Search: React.FC = () => {
const [inputValue, setInputValue] = useState<string>(getLocalInputValue());
function getLocalInputValue(): string {
const localInputValue = localStorage.getItem('input');
return localInputValue !== null ? localInputValue : 'enter text';
}
const changeInput = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
localStorage.setItem('input', event.target.value);
};
return (
<section className="search" data-testid="search">
<div className="wrapper">
<input
className="search_input"
placeholder="Search ..."
autoComplete="off"
autoFocus
name="search"
value={inputValue}
tabIndex={0}
onChange={changeInput}
/>
<div className="search_icon">
<img src={search} alt="search icon" className="icon" />
</div>
</div>
</section>
);
};
export default Search;
|
<script lang="ts">
/* Svelte */
import { session } from "$app/stores";
import { slide } from "svelte/transition";
import { createEventDispatcher } from "svelte";
import type { Event } from "$helpers/interfaces/events";
import type { User } from "$helpers/interfaces/user";
import { modal } from "$stores/modal";
import { Alert, notifications } from "$stores/notifications";
import Gear from "$svg/admin/Gear.svelte";
import Trash from "$svg/admin/Trash.svelte";
import UserDelete from "$svg/admin/UserDelete.svelte";
import UserSettings from "$svg/admin/UserSettings.svelte";
import { API_URL } from "env";
import UserModal from "./UserModal.svelte";
import EventModal from "./EventModal.svelte";
import type { ContactForm } from "$helpers/interfaces/contact-forms";
import Info from "$svg/Info.svelte";
import Checkbox from "$uikit/Checkbox.svelte";
export let type: "users" | "events" | "contacts" = "users";
export let data: User | Event | ContactForm;
const dispatch = createEventDispatcher();
let isModalDisplayed: boolean = false;
const showDeleteModal = (type, data) => {
modal.show({
title: "Attention !",
desc:
type === "users"
? "Vous êtes sur le point de supprimer un utilisateur.<br />Êtes-vous sûr de vouloir continuer ?"
: type === "events"
? "Vous êtes sur le point de supprimer un évènement.<br />Êtes-vous sûr de vouloir continuer ?"
: "Vous êtes sur le point de supprimer un message.<br />Êtes-vous sûr de vouloir continuer ?",
btn1: "Confirmer",
btn2: "Annuler",
action_btn1: () => {
deleteData(data);
modal.remove();
},
action_btn2: () => {
modal.remove();
},
displayCrossBtn: true,
});
};
const deleteData = async (data) => {
try {
const res = await fetch(
`${API_URL}/${type}/delete/${data._id}`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: "Bearer " + $session.token,
},
}
);
if (res.status === 200) {
notifications.add(
new Alert(
`${
type === "users"
? "Utilisateur"
: type === "events"
? "Évènement"
: "Message"
} supprimé !`,
"success"
)
);
dispatch("delete", { id: data._id });
} else {
notifications.add(
new Alert(
"Oups ! Une erreur est survenue...",
"error"
)
);
}
} catch (err) {
console.error("err:", err);
notifications.add(
new Alert(
"Oups ! Une erreur est survenue...",
"error"
)
);
}
};
const update = (e) => {
if (e.detail.user) data = e.detail.user;
if (e.detail.event) data = e.detail.event;
dispatch("update", { event: data });
isModalDisplayed = false;
};
const updateContact = async (e) => {
const contacted: boolean = e.detail;
try {
const res = await fetch(
`${API_URL}/contacts/update-state/${data._id}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: "Bearer " + $session.token,
},
body: JSON.stringify({
contacted,
}),
}
);
const result = await res.json();
if (res.status === 200) {
data.contacted = contacted;
} else {
notifications.add(
new Alert(
"Oups ! Une erreur est survenue...",
"error"
)
);
}
} catch (err) {
console.error("err:", err);
}
};
</script>
<article on:click class:contacted={data.contacted}>
<div class="col-1">
{type === "contacts"
? data.lastname + " " + data.firstname
: data.name}
</div>
<div class="col-2">
{type === "events" ? data.date : data.email}
</div>
<div class="col-3">
{type === "users"
? data.role
: type === "events"
? data.place
: data.date}
</div>
<div class="settings">
<i on:click={() => (isModalDisplayed = !isModalDisplayed)}>
{#if type === "users"}
<UserSettings color={"#000"} />
{:else if type === "events"}
<Gear />
{:else}
<Info />
{/if}
</i>
<i on:click={() => showDeleteModal(type, data)}>
{#if type === "users"}
<UserDelete />
{:else}
<Trash />
{/if}
</i>
</div>
{#if isModalDisplayed && type === "contacts"}
<div transition:slide class="form-info">
<h4>Objet : {data.subject}</h4>
<p>{data.message}</p>
<Checkbox
label="Recontacté"
isChecked={data.contacted}
on:toggle-check={updateContact} />
</div>
{/if}
</article>
{#if isModalDisplayed && type === "users"}
<UserModal userInfo={data} on:remove={update} />
{:else if isModalDisplayed && type === "events"}
<EventModal eventInfo={data} on:remove={update} />
{/if}
<style lang="scss">
article {
@include grid-12;
@include body1;
width: 100%;
padding: $sp-300 $sp-400;
background-color: $grey-300;
@include br-500;
@include ds-300;
@include transition($transition);
&:hover {
@include ds-500;
@include transform(scale(1.02));
@include transition($transition);
}
&.contacted {
background-color: rgba($success, 0.15);
}
& > * {
@include flex-y;
}
.col-1 {
grid-column: 1 / 4;
@include caption-light;
}
.col-2 {
grid-column: 4 / 8;
justify-content: center;
}
.col-3 {
grid-column: 8 / 11;
justify-content: center;
}
.settings {
grid-column: 11 / 13;
justify-content: flex-end;
i {
cursor: pointer;
width: 2rem;
&:first-child:hover {
:global(path) {
fill: $prim-700;
}
}
&:last-child {
margin-left: $sp-300;
&:hover {
:global(path) {
fill: $danger-700;
}
}
}
}
}
.form-info {
display: block;
grid-row: 2;
grid-column: 1 / -1;
& > * {
text-align: left;
&:not(:last-child) {
margin-bottom: $sp-200;
}
}
p {
padding: $sp-200;
background-color: $white;
@include br-300;
}
}
}
</style>
|
import {
Body,
Controller,
Delete,
Get,
Param,
ParseIntPipe,
Patch,
Post,
Query,
UseGuards,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { TaskStatusValidationPipe } from './custom_pipes/task_status_validation_pipes';
import { CreateTaskDto } from './dto/create-task.dto';
import { GetTasksByFilterDto } from './dto/get-tasks-filter-dto';
import { TaskStatus } from './task-status.enum';
import { Task } from './task.entity';
import { TasksService } from './tasks.service';
import { AuthGuard } from '@nestjs/passport';
import { GetUser } from 'src/authentication/GetUserDecorator';
import { User } from 'src/authentication/User';
import { UpdateTaskDto } from './dto/UpdateTaskDto';
@ApiTags("tasks")
@Controller('tasks')
@UseGuards(AuthGuard())
export class TasksController {
constructor(private tasksService: TasksService) { }
@Get()
getTasks(@GetUser() user: User, @Query(ValidationPipe) filterParamsDto: GetTasksByFilterDto) {
return this.tasksService.getTasks(filterParamsDto, user);
}
@Get(':id')
getTaskById(@GetUser() user: User, @Param('id', ParseIntPipe) id: number): Promise<Task> {
return this.tasksService.getTaskById(id, user);
}
@Post()
@UsePipes(ValidationPipe)
createTask(@GetUser() user: User, @Body() createTaskDto: CreateTaskDto): Promise<Task> {
console.log('in create controller');
return this.tasksService.createTask(createTaskDto, user);
}
@Patch(':id')
updateTask(@GetUser() user: User, @Param('id', ParseIntPipe) id: number, @Body() updateTaskDto: UpdateTaskDto): Promise<Task> {
return this.tasksService.updateTask(id, user, updateTaskDto);
}
@Patch(':id/status')
updateTaskStatus(
@GetUser() user: User,
@Param('id', ParseIntPipe) id: number,
@Body('status', TaskStatusValidationPipe) status: TaskStatus,
): Promise<Task> {
return this.tasksService.updateTaskStatus(id, status, user);
}
@Delete(':id')
deleteTask(@GetUser() user: User, @Param('id', ParseIntPipe) id: number): Promise<void> {
return this.tasksService.deleteTask(id, user);
}
}
|
import { Button, Form, message } from "antd";
import { useContext, useEffect } from "react";
import FormItemsGenerator from "../../components/FormItemsGenerator/FormItemsGenerator";
import { data } from "../../Data/data";
import { getNextFieldByJumpingLogic } from "../../utils/NextFieldDecider";
import "./ServeyForm.css";
import ServeyContext from "../../utils/contexts/ServeyContext/ServeyContext";
const ServeyForm = () => {
const {
fieldList,
currentGroupType,
currentField,
setFieldList,
isSubmit,
setIsSubmit,
nextField,
setScroll,
scroll,
form
} = useContext(ServeyContext);
useEffect(() => {
window.scrollTo({
top: document.documentElement.scrollHeight,
behavior: 'smooth'
});
}, [scroll]);
const onFinish = (values) =>{
console.log("Submitted values" ,values);
}
const onFinishFailed = () => {
message.error("Check if all fields are filled properly");
}
const handleNextButton = () => {
setScroll(!scroll); //scroll to next button
// form.validateFields().then(()=>{
if(currentGroupType === 'numbervalidation' || currentGroupType === "non-referring"){
const {jumping_logic} = data.find((group)=> group?.group === currentField?.group);
const next = getNextFieldByJumpingLogic(jumping_logic,form.getFieldsValue());
if(next.blockId === "submit"){
setIsSubmit(true);
}
else{
setIsSubmit(false);
setFieldList((prev) => [...prev,next]);
}
}
else if(!fieldList.some((item) => JSON.stringify(item) === JSON.stringify(nextField))){
setFieldList((prev)=>[...prev,nextField]);
}
// }).catch((err)=>{
// console.log(err);
// })
}
return(<>
<Form
onFinishFailed={onFinishFailed}
className="servey-form"
scrollToFirstError
autoComplete="on"
initialValues={{ remember: true }}
form={form}
onFinish={onFinish}
layout="vertical"
>
{fieldList.map((field,index) => (
<FormItemsGenerator key={index} currentField={field}/>
)
)}
{isSubmit ? (
<Form.Item>
<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
):(
<Form.Item>
<Button onClick={handleNextButton}>Next</Button>
</Form.Item>
)}
</Form>
</>);
};
export default ServeyForm;
// import React, { useState } from 'react';
// import { Form, Input, Button } from 'antd';
// const ServeyForm = () => {
// const [form] = Form.useForm();
// const [currentFieldIndex, setCurrentFieldIndex] = useState(0);
// const fields = [
// { name: 'field1', label: 'Field 1' },
// { name: 'field2', label: 'Field 2' },
// { name: 'field3', label: 'Field 3' },
// // Add more fields as needed
// ];
// const handleNext = () => {
// form.validateFields().then(() => {
// setCurrentFieldIndex((prevIndex) => prevIndex + 1);
// form.resetFields();
// });
// };
// const renderFormItems = () => {
// const formItems = fields.slice(0, currentFieldIndex + 1).map((field) => (
// <Form.Item key={field.name} label={field.label} name={field.name} rules={[{ required: true, message: 'Field is required' }]}>
// <Input />
// </Form.Item>
// ));
// return formItems;
// };
// return (
// <Form form={form} layout="vertical">
// {renderFormItems()}
// {currentFieldIndex < fields.length - 1 && (
// <Button type="primary" onClick={handleNext}>
// Next
// </Button>
// )}
// </Form>
// );
// };
// export default ServeyForm;
|
package Refactorizacion.Tarjeta;
import java.util.ArrayList;
import java.util.List;
import Refactorizacion.ControladorDeArchivos;
import Refactorizacion.OperacionTarjeta.MovimientoR;
public class EstadoCuenta {
private List<MovimientoR> movimientoRs = new ArrayList<>();
public String obtenerEstadoCuenta(TarjetaCredito tarjeta) {
String reporteHTML = "<h3>Consulta de Tarjeta: " + tarjeta.getNumeroDeTarjeta() + "</h3>" +
" <table style=\"border-collapse: collapse;\">\n" +
" <tr>\n" +
" <td colspan=\"5\" style=\"border: 1px solid #000000;\"> NUMERO DE TARJETA: " + tarjeta.getNumeroDeTarjeta() + "</td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td colspan=\"5\" style=\"border: 1px solid #000000;\"> NOMBRE DEL CLIENTE: " + tarjeta.getNombreDelCliente() + "</td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td colspan=\"5\" style=\"border: 1px solid #000000;\"> DIRECCION DEL CLIENTE: " + tarjeta.getDireccionDelCliente() + "</td>\n" +
" </tr>\n";
reporteHTML+= reporteMovimientos(tarjeta.getMovCount(), tarjeta.getNumeroDeTarjeta());
reporteHTML +=" <tr>\n" +
" <td colspan=\"5\" style=\"border: 1px solid #000000;\"> MONTO TOTAL: " + tarjeta.getCredito() + "</td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td colspan=\"5\" style=\"border: 1px solid #000000;\"> INTERESES: " + tarjeta.getCredito() + "</td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td colspan=\"5\" style=\"border: 1px solid #000000;\"> INTERESES: " + tarjeta.getSaldoTotal() + "</td>\n" +
" </tr>\n" +
" </table>";
return reporteHTML;
}
private String reporteMovimientos(int num, String name){
obtenerMovimientos(num, name);
String reporte = " <tr>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> FECHA </td>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> TIPOMOVIMIENTO </td>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> DESCRIPCION </td>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> ESTABLECIMIENTO </td>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> MONTO </td>\n" +
" </tr>\n" ;
for (MovimientoR movimientoR : movimientoRs) {
reporte+= " <tr>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> " + movimientoR.getFecha() + " </td>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> " + movimientoR.getTipoDeMovimiento() + " </td>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> " + movimientoR.getDescripcion() + " </td>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> " + movimientoR.getEstablecimiento() + " </td>\n" +
" <td colspan=\"1\" style=\"border: 1px solid #000000;\"> " + movimientoR.getMonto() + " </td>\n" +
" </tr>\n" ;
}
return reporte;
}
private void obtenerMovimientos(int num, String name){
ControladorDeArchivos controler = new ControladorDeArchivos();
for (int i = 0; i < num; i++) {
String nombre = "Movimiento"+name+(i+1)+".mvito";
MovimientoR aux = controler.leerMovimiento(nombre);
if(aux!=null){
movimientoRs.add(aux);
}
}
}
}
|
import React from "react";
import Author from "./Author";
import Tweet from "./Tweet";
import NewQuote from "./NewQuote";
import Quote from "./Quote";
import { useState, useEffect } from "react";
import { data } from "../data/data.js";
function QuoteBox() {
const [rgbValue, setRgbValue] = useState([0, 0, 0]);
const [quote, setQuote] = useState(data[0]);
const bgColorHandler = () => {
let red = Math.floor(Math.random() * 256);
let green = Math.floor(Math.random() * 256);
let blue = Math.floor(Math.random() * 256);
let index = Math.floor(Math.random() * data.length);
setQuote(data[index]);
setRgbValue([red, green, blue]);
};
useEffect(() => {
document.documentElement.style.setProperty(
"--text-color",
`rgb(${rgbValue[0]}, ${rgbValue[1]}, ${rgbValue[2]})`
);
document.documentElement.style.setProperty(
"--background-color",
`rgb(${rgbValue[0]}, ${rgbValue[1]}, ${rgbValue[2]})`
);
}, [rgbValue]);
return (
<div id="quote-box" className="container">
<div className="row m-4">
<Quote newQuote={quote} />
</div>
<div className="row m-4">
<Author newAuthor={quote.author} />
</div>
<div className="row m-4">
<Tweet />
<NewQuote colorHandler={bgColorHandler} />
</div>
</div>
);
}
export default QuoteBox;
|
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:o="http://omnifaces.org/ui"
>
<o:importConstants type="mjb44.calculator_with_navigation.SessionKeys"/>
<h:head>
<title>Calculator</title>
</h:head>
<h:body>
<f:view>
<div>
<span>Welcome #{sessionScope[SessionKeys.LOGGEDIN_USER]}!</span>
<h:form>
<h:commandButton value="logout" action="#{user.logout}"/>
</h:form>
</div>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel value="left"></h:outputLabel>
<h:inputText id="left" value="#{calculator.left}"></h:inputText>
<h:message for="left"></h:message>
<h:outputLabel value="right"></h:outputLabel>
<h:inputText id="right" value="#{calculator.right}">
</h:inputText>
<h:message for="right"></h:message>
</h:panelGrid>
<h:commandButton action="#{calculator.show}" value="show"></h:commandButton>
<h:commandButton action="#{calculator.clear}" value="reset"
immediate="true"></h:commandButton>
<h:messages layout="table"></h:messages>
</h:form>
<h:panelGrid rendered="#{calculator.result!=0}" columns="3">
<h:form>
<h:outputLabel value="#{result}"></h:outputLabel>
<h:inputText id="result" value="#{calculator.result}">
</h:inputText>
<h:message for="result"></h:message>
</h:form>
</h:panelGrid>
</f:view>
</h:body>
</html>
|
import _ from "lodash";
import css from "./styles.module.scss";
import {ReactComponent as ArrowRight} from "@/assets/icons/arrow/carousel-right.svg";
import {ReactComponent as ArrowLeft} from "@/assets/icons/arrow/carousel-left.svg";
interface Props {
totalQty: number;
pageSize: number;
page: number;
onChangePage: (page: number) => void;
}
export const NumberPaginator = ({totalQty, pageSize, page, onChangePage}: Props) => {
const pageCount = Math.ceil(totalQty / pageSize);
const nextPage = () => {
if (page + 1 < pageCount)
onChangePage(page + 1);
};
const prevPage = () => {
if (page - 1 >= 0)
onChangePage(page - 1);
};
const setPage = (page: number) => {
onChangePage(page);
};
return (
<div className={css.pagination}>
<ArrowLeft className={css.paginationButton} onClick={prevPage}/>
{
_.range(pageCount)
.map((_, index) =>
<p
key={index}
className={page === index ? css.activePage : css.pages}
onClick={() => setPage(index)}
>
{index + 1}
</p>
)
}
<ArrowRight className={css.paginationButton} onClick={nextPage}/>
</div>
);
};
|
//
// SignInView.swift
// coRat
//
// Created by Yuki-OHMORI on 2023/08/28.
//
import SwiftUI
import Foundation
import PDFKit
import FirebaseAuth
import FirebaseFirestore
import CoreLocation
struct SignInView: View {
@State var gender = ""
@State var dateOfBirth:Date = Calendar.current.date(from: DateComponents(year: 1990, month: 1, day: 1))!
@State var socialAttribute=""
@State var signInState = false
@State var addressEroor = false
@State var addressAlert = false
@State var errorMassege = ""
@State var zipCord = 0
@State var address = ""
@State var country = "Japan"
let genderArray = ["Female","Male","Other"]
let socialAttributeArray = [
"Company employee",
"Civil servant",
"Self-employed",
"Company officer",
"Freelance",
"Housewife",
"Elementary school student",
"Junior high school student",
"High school student",
"College or university student",
"Graduate student",
"Part-time job",
"Unemployed"
]
let geocoder = CLGeocoder()
var body: some View {
NavigationStack{
VStack{
Text("Sign in")
Text(errorMassege)
Form{
Section{
VStack{
Picker(selection: $gender, label: Text("Enter your gender")){
ForEach(genderArray, id: \.self){ item in
Text(item)
}
}
DatePicker("Pick your date of birth",selection: $dateOfBirth,displayedComponents: .date)
//個人情報{生年月日,社会的属性,住所}
//同意
Picker(selection: $socialAttribute, label: Text("Enter your gender")){
ForEach(socialAttributeArray, id: \.self){ item in
Text(item)
}
}
Text("If you live in Japan,Enter your ZIP Code")
TextField("",value:$zipCord,format:.number).keyboardType(.numberPad)
Text("If you don't live in Japan Pick country you live in")
TextField("",text:$country)
}
}
Section{
VStack{
Button(action: {
let user = Auth.auth().currentUser
if gender != "" && socialAttribute != ""{
if let user = user{
let uid = user.uid
Firestore.firestore().collection("user").document(uid).setData(["uid":uid,"dateOfBirth":dateOfBirth,"gender":gender,"socialAttribute":socialAttribute])
geocoder.geocodeAddressString("\(zipCord)", completionHandler: {(placemarks, error) -> Void in if error != nil{
addressEroor = true
}
if let placemark = placemarks?.first{
address = "\(placemark.administrativeArea)\(placemark.locality)\(placemark.subLocality)"
addressAlert = true
}
})
}
}else{
errorMassege = "Please enter information!!"
}
}){
Text("Sign in")
NavigationLink(destination: ContentView(),isActive:$signInState){}
}.alert(title:Text("error"),message:Text("The address could not be correctly queried from the zip code. Please check your internet connection and zip code."), isPresented: $addressEroor)
.alert(title:Text("confirmation"),message:Text("Is \(address) your correct address?"),isPresented: $addressAlert, primaryButton: .default(Text("OK"){
signInState = true
}),secondaryButton: .cancel(Text("Cancel"){addressAlert = false}))
}
}
}
}
}
}
struct SignInView_Previews: PreviewProvider {
static var previews: some View {
SignInView()
}
}
}
|
import React from "react";
import Search from "./components/Search";
import styles from "./style.module.css";
import { ReactComponent as Profile } from "../../assets/Profile.svg";
import SideBar from "./components/SideBar";
import { useState } from "react";
function Header() {
let [show, setShow] = useState(false);
function handleClick() {
setShow(!show);
}
return (
<header className={styles.header}>
<div className={styles.subheader}>
<h3>Team Inbox</h3>
</div>
<div className={styles.subheader}>
<Search className={styles.search} />
<Profile onClick={handleClick} className={styles.profile} />
{show && <SideBar show={show} setShow={setShow} />}
</div>
</header>
);
}
export default Header;
|
function Finish({ points, maxPoints, highscore, dispatch }) {
const percent = (points / maxPoints) * 100;
let emoji;
if (percent === 100) emoji = "🥳🥳";
if (percent >= 80 && percent < 100) emoji = "🎖️👍";
if (percent >= 50 && percent < 80) emoji = "🙌✨";
if (percent >= 30 && percent < 50) emoji = "🫤🫠";
if (percent < 30) emoji = "🥴🤦♂️";
return (
<>
<p className="result">
{emoji} You have scored <strong>{points}</strong> out of {maxPoints} (
{Math.ceil(percent)} %)
</p>
<p className="highscore">HighScore is {highscore}</p>
<button
className="btn btn-ui"
onClick={() => dispatch({ type: "reset" })}
>
Reset Quiz
</button>
</>
);
}
export default Finish;
|
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using School_API.Services;
using School_Data.DTOs;
using School_Data.Helpers;
using School_Data.Models;
using System.Net;
namespace School_API.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class AuthController : ControllerBase
{
private readonly IAuthService _authService;
private readonly ILogger<AuthController> _logger;
private readonly IMapper _mapper;
protected APIResponse _resp;
public AuthController(IAuthService authService, ILogger<AuthController> logger, IMapper mapper)
{
_authService = authService;
_logger = logger;
_mapper = mapper;
_resp = new();
}
/// <summary>
/// Sirve para acceder al API.
/// </summary>
/// <param name="model">Datos para acceder</param>
/// <returns>Retorno de datos sobre acceso al API.</returns>
[HttpPost]
[Route("login")]
//[SwaggerResponse(StatusCodes.Status400BadRequest)]
//[SwaggerResponse(StatusCodes.Status500InternalServerError)]
//[SwaggerResponse(StatusCodes.Status200OK, Type = typeof(Task<APIResponse>))]
public async Task<APIResponse> Login(LoginModel model)
{
try
{
if (!ModelState.IsValid)
{
_logger.LogError("Error en algunos campos.");
_resp.IsValid = false;
_resp.Message = "Error en algunos campos.";
_resp.StatusCode = HttpStatusCode.BadRequest;
return _resp;
}
_logger.LogInformation("Enviando respuesta correcta desde login.");
return await _authService.Login(model);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_resp.IsValid = false;
_resp.Message = "Error interno sistema.";
_resp.StatusCode = (HttpStatusCode)StatusCodes.Status500InternalServerError;
_resp.ErrorMessages = new List<string> { ex.Message };
return _resp;
}
}
/// <summary>
/// Silve para registrar el usuario.
/// </summary>
/// <param name="model">Datos para registrarse</param>
/// <returns>Respuesta sobre datos que son aceptados o rechazados</returns>
[HttpPost]
[Route("registeration")]
[Authorize(Roles = "Admin")]
public async Task<APIResponse> Register(RegistrationModel model)
{
try
{
if (!ModelState.IsValid)
{
_logger.LogError("Error en algunos campos.");
_resp.IsValid = false;
_resp.Message = "Error en algunos campos.";
_resp.StatusCode = HttpStatusCode.BadRequest;
return _resp;
}
_resp = await _authService.Registeration(model, model.Role);
_logger.LogInformation("Enviando respuesta desde Register.");
return _resp;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_resp.IsValid = false;
_resp.Message = "Error interno sistema.";
_resp.StatusCode = (HttpStatusCode)StatusCodes.Status500InternalServerError;
_resp.ErrorMessages = new List<string> { ex.Message };
return _resp;
}
}
/// <summary>
/// Cambiar su contraseña
/// </summary>
/// <param name="model">Datos para cambiar</param>
/// <returns>Respuesta sobre datos que son aceptados o rechazados</returns>
[HttpPost]
[Route("ChangePassword")]
public async Task<APIResponse> ChangePassword(UserChangePasswordDTO model)
{
try
{
if (!ModelState.IsValid)
{
_logger.LogError("Error en algunos campos.");
_resp.IsValid = false;
_resp.Message = "Error en algunos campos.";
_resp.StatusCode = HttpStatusCode.BadRequest;
return _resp;
}
_resp = await _authService.ChangePassword(model);
return _resp;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
_resp.IsValid = false;
_resp.Message = "Error interno sistema.";
_resp.StatusCode = (HttpStatusCode)StatusCodes.Status500InternalServerError;
_resp.ErrorMessages = new List<string> { ex.Message };
return _resp;
}
}
}
}
|
import React, { useEffect, useState } from 'react';
import { View, Text, Image, StyleSheet, FlatList } from 'react-native';
import axios from 'axios';
import { Card } from 'react-native-elements';
function PokeInfo({ pokeName }) {
const [pokemonData, setPokemonData] = useState(null);
const [generationData, setGenerationData] = useState(null);
const apiUrl = `https://pokeapi.co/api/v2/pokemon/${pokeName}`;
const speciesUrl = `https://pokeapi.co/api/v2/pokemon-species/${pokeName}`;
useEffect(() => {
axios
.get(apiUrl)
.then((response) => {
setPokemonData(response.data);
})
.catch((error) => {
console.error('Error al obtener datos de la API', error);
});
axios
.get(speciesUrl)
.then((response) => {
const generationUrl = response.data.generation.url;
axios.get(generationUrl).then((genResponse) => {
setGenerationData(genResponse.data);
});
})
.catch((error) => {
console.error('Error al obtener datos de la API', error);
});
}, [pokeName]);
if (!pokemonData || !generationData) {
return null;
}
return (
<View style={styles.container}>
<Card style={styles.card}>
<Text style={styles.pokemonName}>
{pokemonData.name.charAt(0).toUpperCase() + pokemonData.name.slice(1)}
</Text>
<Image
source={{
uri: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonData.id}.png`,
}}
style={{ width: 300, height: 300 }}
/>
<Text style={styles.boldText}>Generación:</Text>
<Text>{generationData.name}</Text>
<View style={styles.infoContainer}>
<View style={styles.column}>
<Text style={styles.boldText}>Altura:</Text>
<Text>{pokemonData.height}</Text>
<Text style={styles.boldText}>Especie:</Text>
<Text>{pokemonData.species.name}</Text>
</View>
<View style={styles.column}>
<Text style={styles.boldText}>Peso:</Text>
<Text>{pokemonData.weight}</Text>
<Text style={styles.boldText}>Tipo:</Text>
<Text>{pokemonData.types[0].type.name}</Text>
</View>
</View>
<View style={styles.statsHeader}>
<Text style={styles.boldText}>Estadísticas Base:</Text>
</View>
<View style={styles.statsContainer}>
{pokemonData.stats.map((stat) => (
<View key={stat.stat.name} style={styles.stat}>
<Text style={styles.boldText}>{stat.stat.name}:</Text>
<Text>{stat.base_stat}</Text>
</View>
))}
</View>
</Card>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 16,
},
card: {
margin: 8,
},
pokemonName: {
textAlign: 'center',
fontSize: 24,
fontWeight: 'bold',
},
infoContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
},
column: {
flex: 1,
},
statsContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
flexWrap: 'wrap',
},
stat: {
width: '45%',
marginBottom: 10,
alignItems: 'center',
},
boldText: {
fontWeight: 'bold',
},
centeredText: {
textAlign: 'center',
},
statsHeader: {
marginTop: 10,
},
});
export default PokeInfo;
|
//
// DebugView.swift
// Posterr
//
// Created by Elton Jhony on 11.07.22.
//
import Foundation
import SwiftUI
struct DebugView: View {
@ObservedObject var viewModel: ViewModel
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack(spacing: 24) {
Text("Select the current user")
ForEach(viewModel.users, id: \.uuid) { user in
VStack(alignment: .leading) {
Text(user.username)
}
.frame(width: UIScreen.main.bounds.width)
.padding()
.background(user.isCurrent ? .appPrimary : Color.white)
.onTapGesture {
viewModel.select(new: user)
}
}
Spacer()
}
.padding(.vertical)
.onAppear(perform: viewModel.onAppear)
.onChange(of: viewModel.dismiss) { newValue in
presentationMode.wrappedValue.dismiss()
}
}
}
// MARK: Shake Detection
extension UIWindow {
override open func becomeFirstResponder() -> Bool {
true
}
override open func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
guard motion == .motionShake else { return }
let viewController = UIHostingController(rootView: DebugView(viewModel: PosterrAssembler.resolve(DebugView.ViewModel.self)))
rootViewController?.present(viewController, animated: true)
}
}
|
// print_receipt.dart
import 'package:flutter_sunmi_printer_plus/column_maker.dart';
import 'package:flutter_sunmi_printer_plus/flutter_sunmi_printer_plus.dart';
import 'package:flutter_sunmi_printer_plus/sunmi_style.dart';
import 'package:flutter_sunmi_printer_plus/enums.dart';
import 'package:flutter/services.dart';
Future<Uint8List> readFileBytes(String path) async {
try {
ByteData fileData = await rootBundle.load(path);
Uint8List fileUnit8List = fileData.buffer
.asUint8List(fileData.offsetInBytes, fileData.lengthInBytes);
return fileUnit8List;
} catch (err) {
rethrow;
}
}
Future<Uint8List> _getImageFromAsset(String iconPath) async {
return await readFileBytes(iconPath);
}
Future<void> printReceipt() async {
Uint8List bytes = await _getImageFromAsset('assets/images/xash_logo.jpg');
await SunmiPrinter.printImage(image: bytes, align: SunmiPrintAlign.CENTER);
await SunmiPrinter.lineWrap(2);
await SunmiPrinter.printText(
content: "Josbo Inc. Tuckshop",
style: SunmiStyle(
fontSize: 30,
isUnderLine: false,
bold: true,
align: SunmiPrintAlign.CENTER));
await SunmiPrinter.lineWrap(3);
await SunmiPrinter.printText(
content: "Xash Vent to the world",
style: SunmiStyle(
fontSize: 20,
isUnderLine: false,
bold: true,
align: SunmiPrintAlign.CENTER));
await SunmiPrinter.lineWrap(3);
await SunmiPrinter.printTable(cols: [
ColumnMaker(text: "1235555 XV1", align: SunmiPrintAlign.LEFT, width: 10),
ColumnMaker(text: "XV 3333333", align: SunmiPrintAlign.LEFT, width: 10),
ColumnMaker(text: "Last One", align: SunmiPrintAlign.LEFT, width: 10),
]);
await SunmiPrinter.printTable(cols: [
ColumnMaker(text: "TESTHERE!", align: SunmiPrintAlign.LEFT, width: 15),
ColumnMaker(text: "OH-MAN", align: SunmiPrintAlign.LEFT, width: 15),
]);
await SunmiPrinter.lineWrap(2);
await SunmiPrinter.printBarCode(
data: "1234567890",
height: 50,
width: 2,
textPosition: SunmiBarcodeTextPos.TEXT_UNDER,
barcodeType: SunmiBarcodeType.CODE128,
align: SunmiPrintAlign.CENTER);
await SunmiPrinter.lineWrap(2);
await SunmiPrinter.printQr(
data: "https://vend.xash.co.zw", align: SunmiPrintAlign.CENTER, size: 5);
await SunmiPrinter.lineWrap(2);
await SunmiPrinter.feedPaper();
await SunmiPrinter.cutPaper();
}
|
<?php
namespace Tests\Functional\Domain\User\Command\Profile\Handler;
use App\Bridge\Xenforo\ForumApiInterface;
use App\Bridge\Xenforo\Provider\Mock\UserProvider;
use App\Domain\User\Command\Profile\UpdateBasicInformationCommand;
use App\Domain\User\Entity\User;
use App\Domain\User\Entity\ValueObject\Gender;
use Tests\DataFixtures\ORM\User\LoadTestUser;
use Tests\Functional\TestCase;
class UpdateBasicInformationHandlerTest extends TestCase
{
/** @var User */
private $user;
/** @var ForumApiInterface */
private $forumApi;
protected function setUp(): void
{
parent::setUp();
$referenceRepository = $this->loadFixtures([
LoadTestUser::class,
])->getReferenceRepository();
$this->user = $referenceRepository->getReference(LoadTestUser::USER_TEST);
$this->forumApi = $this->getContainer()->get(ForumApiInterface::class);
}
protected function tearDown(): void
{
unset(
$this->command,
$this->forumApi
);
parent::tearDown();
}
public function testUserMustBeUpdatedByCommandData(): void
{
$command = new UpdateBasicInformationCommand($this->user);
$command->login = $this->getFaker()->unique()->userName;
$command->email = 'test@gmail.com';
$command->name = $this->getFaker()->realText(100);
$command->gender = (string) Gender::MALE();
$command->birthdate = $this->getFaker()->dateTime();
$command->cityName = 'Новосибирск';
$command->cityCountry = 'Россия';
$this->getCommandBus()->handle($command);
$this->assertEquals($command->login, $this->user->getLogin());
$this->assertEquals($command->email, $this->user->getEmailAddress());
$this->assertEquals($command->name, $this->user->getName());
$this->assertEquals($command->gender, $this->user->getGender());
$this->assertEquals($command->birthdate, $this->user->getBirthdate());
$this->assertEquals($command->cityName, $this->user->getCity()->getName());
$this->assertEquals($command->cityCountry, $this->user->getCity()->getCountry());
}
public function testUpdatedUserShouldBeAlsoUpdatedInForum(): void
{
$command = new UpdateBasicInformationCommand($this->user);
$this->getCommandBus()->handle($command);
/** @var UserProvider $forumUserProvider */
$forumUserProvider = $this->forumApi->user();
$this->assertTrue($forumUserProvider->isUserUpdated($this->user));
}
public function testAfterUpdatingEmailUserMustReceiveConfirmationLink(): void
{
$command = new UpdateBasicInformationCommand($this->user);
$command->email = 'updated'.$this->user->getEmailAddress();
$this->getCommandBus()->handle($command);
$mailWithConfirmationLink = $this->loadLastEmailMessage();
$this->assertNotEmpty($mailWithConfirmationLink);
$this->assertStringContainsString($command->email, $mailWithConfirmationLink);
$this->assertStringContainsString('Для завершения регистрации, пожалуйста, пройдите по ссылке ниже', $mailWithConfirmationLink);
}
}
|
# 만들어둔 UserForm을 Import하여 사용한다.
from apps.crud.forms import UserForm
from flask import Blueprint, render_template, redirect, url_for
from apps.crud.models import User
from apps.app import db
from flask_login import login_required
# Blueprint로 crud 앱을 생성한다.
crud = Blueprint(
"crud",
__name__,
template_folder="templates",
static_folder="static",
)
# index 엔드 포인트를 작성하고 index.html을 반환한다.
@crud.route("/")
@login_required
def index():
return render_template("crud/index.html")
# 새 회원을 등록하기 위한 엔드포인트(route)를 생성한다.
@crud.route("/users/new", methods=["GET","POST"])
@login_required
def create_user():
#UserForm을 인스턴스화한다.
form = UserForm()
# 폼의 값을 검증한다.
if form.validate_on_submit():
# 사용자를 작성한다.
user = User(
username=form.username.data,
email=form.email.data,
password=form.password.data,
)
# 사용자를 추가하고 커밋한다.
db.session.add(user)
db.session.commit()
# 사용자의 일람 화면으로 리다이렉트 한다.
return redirect(url_for("crud.users"))
return render_template("crud/create.html", form=form)
# 회원들 리스트를 볼수 있는 화면을 만든다.
@crud.route("/users",methods=["GET"])
@login_required
def users():
"""사용자의 일람을 취득한다."""
users = User.query.all()
return render_template("crud/index.html", users=users)
# 회원정보를 수정하는 화면을 만든다. methods에 GET과 POST를 지정한다.
@crud.route("/users/<user_id>", methods=["GET","POST"])
@login_required
def edit_user(user_id):
form = UserForm()
# User 모델을 이용하여 사용자를 취득한다.
user = User.query.filter_by(id=user_id).first()
# form으로부터 제출된 경우는 사용자를 갱신하여 사용자의 열람 화면으로 리다이렉트한다.
if form.validate_on_submit():
user.username = form.username.data
user.email = form.email.data
user.password = form.password.data
db.session.add(user)
db.session.commit
return redirect(url_for("crud.users"))
# GET의 경우는 HTML을 반환한다.
return render_template("crud/edit.html", user=user, form=form)
#사용자를 삭제하는 화면 만들기
@crud.route("/users/<user_id>/delete", methods=["POST"])
@login_required
def delete_user(user_id):
user=User.query.filter_by(id=user_id).first()
db.session.delete(user)
db.session.commit()
return redirect(url_for("crud.users"))
|
#include "lvgl_plus.hh"
#include "lvgl.h"
#include "lvgl_display.hh"
#include "widgets/message_box.hh"
#include <memory>
#include <thread>
namespace softeq
{
namespace lvglplus
{
std::recursive_mutex LvglPlus::_lvglMutex;
uint8_t LvglPlus::DisplayContainer::idCounter = 0;
std::list<std::shared_ptr<LvglPlus::DisplayContainer>> LvglPlus::_displayContainer;
bool LvglPlus::_lvglInitialized = false;
bool LvglPlus::_exitFlag = false;
LvglPlus::~LvglPlus()
{
lv_deinit();
}
void LvglPlus::stopApp()
{
_exitFlag = true;
}
void LvglPlus::runApp(bool drawOnce)
{
_exitFlag = drawOnce;
for (const auto &displayContainer : _displayContainer)
{
static_cast<Renderable *>(displayContainer->rootWidget.get())->renderWithChildren();
}
UniqueLock locker(lvglMutex());
locker.unlock();
do
{
locker.lock();
lv_task_handler();
locker.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(5));
} while (!_exitFlag);
}
void LvglPlus::initialize()
{
/*Initialize LVGL*/
if (!_lvglInitialized)
{
lv_init();
_lvglInitialized = true;
}
}
void LvglPlus::setScreen(const std::shared_ptr<Widget> &screen, std::shared_ptr<LvglDisplay> display)
{
if (!display)
{
display = findDisplay(0);
}
if (!display)
{
// todo throw Exception "No screen found"
}
else
{
findDisplayContainer(display)->rootWidget->replaceChild(screen);
}
}
std::shared_ptr<LvglDisplay> LvglPlus::findDisplay(uint8_t id)
{
for (const auto &displayContainer : _displayContainer)
{
if (displayContainer->id == id)
{
return displayContainer->lvglDisplay;
}
}
return nullptr;
}
std::shared_ptr<LvglDisplay> LvglPlus::findDisplay(const std::shared_ptr<Widget> &root)
{
for (const auto &displayContainer : _displayContainer)
{
if (displayContainer->rootWidget == root)
{
return displayContainer->lvglDisplay;
}
}
return nullptr;
}
std::shared_ptr<Theme> LvglPlus::findCustomTheme(const std::shared_ptr<Widget> &root)
{
for (const auto &displayContainer : _displayContainer)
{
if (displayContainer->rootWidget == root)
{
return displayContainer->theme;
}
}
return nullptr;
}
std::shared_ptr<Widget> LvglPlus::findRoot(const std::shared_ptr<LvglDisplay> &display)
{
for (const auto &displayContainer : _displayContainer)
{
if (displayContainer->lvglDisplay == display)
{
return displayContainer->rootWidget;
}
}
return nullptr;
}
std::shared_ptr<LvglPlus::DisplayContainer> LvglPlus::findDisplayContainer(std::shared_ptr<LvglDisplay> display)
{
if (!display)
{
display = findDisplay(0);
}
for (auto displayContainer : _displayContainer)
{
if (displayContainer->lvglDisplay == display)
{
return displayContainer;
}
}
return nullptr;
}
std::shared_ptr<LvglPlus::DisplayContainer> LvglPlus::findDisplayContainer(const std::shared_ptr<Widget> &root)
{
for (auto displayContainer : _displayContainer)
{
if (displayContainer->rootWidget == root)
{
return displayContainer;
}
}
return nullptr;
}
void LvglPlus::messageBox(const std::shared_ptr<Widget> &root)
{
LvglPlus::messageBox(root, MessageBoxParamsBuilder());
}
void LvglPlus::messageBox(const std::shared_ptr<Widget> &root, const MessageBoxParamsBuilder &messageBoxBuilder)
{
auto rootWidget = root->root();
auto display = findDisplay(rootWidget);
if (display)
{
auto messageBoxWidget = std::make_shared<MessageBox>(display, messageBoxBuilder);
std::weak_ptr<MessageBox> messageBoxWidgetWeak = messageBoxWidget;
messageBoxWidget->setOnExit(
[rootWidget, messageBoxWidgetWeak]() { rootWidget->removeChild(messageBoxWidgetWeak.lock()); });
rootWidget->addChild(messageBoxWidget);
}
}
void LvglPlus::setCustomTheme(const std::shared_ptr<Widget> &root, const std::shared_ptr<Theme> &theme)
{
auto rootWidget = root->root();
auto displayContainer = findDisplayContainer(rootWidget);
if (displayContainer)
{
auto display = displayContainer->lvglDisplay;
displayContainer->theme = theme;
displayContainer->theme->setDisp(display->lvDisplay());
theme->apply();
}
}
void LvglPlus::removeCustomTheme(const std::shared_ptr<Widget> &root)
{
auto rootWidget = root->root();
auto displayContainer = findDisplayContainer(rootWidget);
if ((displayContainer) && (displayContainer->theme))
{
displayContainer->theme->remove();
displayContainer->theme.reset();
}
}
std::shared_ptr<LvglDisplay> LvglPlus::removeDisplay(lv_disp_t *disp)
{
for (const auto &displayContainer : _displayContainer)
{
if (displayContainer->lvglDisplay->lvDisplay() == disp)
{
_displayContainer.remove(displayContainer);
break;
}
}
}
std::shared_ptr<LvglDisplay> LvglPlus::addDisplay(unsigned short width, unsigned short height,
void (*flushCallback)(struct _lv_disp_drv_t *, const lv_area_t *,
lv_color_t *))
{
auto display = std::make_shared<LvglDisplay>(width, height, flushCallback);
lv_disp_set_default(display->lvDisplay());
auto displayContainer = std::make_shared<DisplayContainer>();
_displayContainer.push_back(displayContainer);
displayContainer->rootWidget = std::make_shared<RootWidget>(display->lvDisplay());
displayContainer->lvglDisplay = display;
return display;
}
std::shared_ptr<LvglDriver> LvglPlus::addMouse(void (*readCallback)(struct _lv_indev_drv_t *, lv_indev_data_t *),
const std::shared_ptr<LvglDisplay> &display)
{
return registerDriver(LV_INDEV_TYPE_POINTER, readCallback, display);
}
std::shared_ptr<LvglDriver> LvglPlus::addKeyboard(void (*readCallback)(struct _lv_indev_drv_t *, lv_indev_data_t *),
const std::shared_ptr<LvglDisplay> &display)
{
return registerDriver(LV_INDEV_TYPE_KEYPAD, readCallback, display);
}
std::shared_ptr<LvglDriver> LvglPlus::addEncoder(void (*readCallback)(struct _lv_indev_drv_t *, lv_indev_data_t *),
const std::shared_ptr<LvglDisplay> &display)
{
return registerDriver(LV_INDEV_TYPE_ENCODER, readCallback, display);
}
std::shared_ptr<LvglDriver> LvglPlus::addButton(void (*readCallback)(struct _lv_indev_drv_t *, lv_indev_data_t *),
const std::shared_ptr<LvglDisplay> &display)
{
return registerDriver(LV_INDEV_TYPE_BUTTON, readCallback, display);
}
std::shared_ptr<LvglDriver> LvglPlus::addDriver(void (*readCallback)(struct _lv_indev_drv_t *, lv_indev_data_t *),
const std::shared_ptr<LvglDisplay> &display)
{
return registerDriver(LV_INDEV_TYPE_NONE, readCallback, display);
}
std::shared_ptr<LvglDriver> LvglPlus::registerDriver(lv_indev_type_t type,
void (*readCallback)(struct _lv_indev_drv_t *, lv_indev_data_t *),
const std::shared_ptr<LvglDisplay> &display)
{
auto displayContainer = findDisplayContainer(display);
auto driver = std::make_shared<LvglDriver>(type, readCallback);
driver->indev()->driver->disp = display->lvDisplay();
displayContainer->lvglDriver.push_back(driver);
return driver;
}
} // namespace lvglplus
} // namespace softeq
|
#!/usr/bin/env python3
from flask import Flask, abort, redirect, request, session, url_for, current_app
from flask.views import MethodView
from flask_saml2.idp import IdentityProvider
from .tests.idp.base import CERTIFICATE, PRIVATE_KEY, User
from .tests.sp.base import CERTIFICATE as SP_CERTIFICATE
class ExampleIdentityProvider(IdentityProvider):
def login_required(self):
if not self.is_user_logged_in():
next = url_for("saml_login", next=request.url)
abort(redirect(next))
def is_user_logged_in(self):
return "saml_user" in session and session["saml_user"] in users
def logout(self):
del session["saml_user"]
def get_current_user(self):
return users[session["saml_user"]]
users = {
user.username: user for user in [
User("alex", "alex@example.com"),
User("jordan", "jordan@example.com"),
]
}
idp = ExampleIdentityProvider()
class Login(MethodView):
def get(self):
options = "".join(
f'<option value="{user.username}">{user.email}</option>'
for user in users.values())
select = f'<div><label>Select a user: <select name="user">{options}</select></label></div>'
next_url = request.args.get("next")
next = f'<input type="hidden" name="next" value="{next_url}">'
password = f'Password: <input name="password">'
submit = '<div><input type="submit" value="Login"></div>'
form = f'<form action="login" method="post">{select}{password}{next}{submit}</form>'
header = "<title>Login</title><p>Please log in to continue.</p>"
return header + form
def post(self):
username = request.form["user"]
password = request.form["password"]
next_url = request.form["next"]
# TODO: if password not match...
if password != "12345":
abort(401)
session["saml_user"] = username
current_app.logger.info(f"Logged user {username} in")
current_app.logger.info(f"Redirecting to {next_url}")
return redirect(next_url)
def setup_saml(app: Flask):
# app.debug = True
if "SECRET_KEY" not in app.config:
app.secret_key = "secret"
app.config["SERVER_NAME"] = "www.svc.deltaww-energy.com:5001"
app.config["SAML2_IDP"] = {
"autosubmit": True,
"certificate": CERTIFICATE,
"private_key": PRIVATE_KEY,
}
app.config["SAML2_SERVICE_PROVIDERS"] = [
{
"CLASS": "sso_server.saml.tests.idp.base.AttributeSPHandler",
"OPTIONS": {
"display_name":
"Example Service Provider A",
"entity_id":
"https://saml-spa.deltaww-energy.com:9000/saml/metadata.xml",
"acs_url":
"https://saml-spa.deltaww-energy.com:9000/saml/acs/",
"certificate":
SP_CERTIFICATE,
},
},
{
"CLASS": "sso_server.saml.tests.idp.base.AttributeSPHandler",
"OPTIONS": {
"display_name":
"Example Service Provider B",
"entity_id":
"https://saml-spb.deltaww-energy.com:9001/saml/metadata.xml",
"acs_url":
"https://saml-spb.deltaww-energy.com:9001/saml/acs/",
"certificate":
SP_CERTIFICATE,
},
},
]
app.add_url_rule("/sso/saml/login", view_func=Login.as_view("saml_login"))
app.register_blueprint(idp.create_blueprint(), url_prefix="/sso/saml/api")
|
<?php
namespace Modules\Core\Concerns;
use App\Models\User;
use BezhanSalleh\FilamentShield\Facades\FilamentShield;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use function Modules\Core\Support\utils;
trait StandardPolicy
{
abstract public function getResourceClass(): string;
public function getSuffix(): string
{
return FilamentShield::getPermissionIdentifier($this->getResourceClass());
}
public function makeSuffixFromModel(Model|string $model): string
{
if (is_string($model)) {
$class = $model::getModel()->getMorphClass();
} else {
$class = $model->getMorphClass();
}
return Str::of(Str::of($class)->explode('\\')->last() ?? '')
->snake('::')->toString();
}
public function viewAny(User $user): bool
{
return $user->can($this->perm('view_any'));
}
public function view(User $user, Model $model): bool
{
return $user->can($this->perm('view'));
}
public function create(User $user): bool
{
return $user->can($this->perm('create'));
}
public function update(User $user, Model $model): bool
{
return ! $this->isImmutable($model) && (! utils()->model_has_record_status($model) || $model->isDraft()) && $user->can($this->perm('update'));
}
public function deleteAny(User $user): bool
{
return $user->can($this->perm('delete_any'));
}
public function delete(User $user, Model $model): bool
{
return ! $this->isImmutable($model) && $user->can($this->perm('delete')) && (! utils()->model_has_record_status($model) || $model->isDraft());
}
public function submit(User $user, Model $model): bool
{
return ! $this->isImmutable($model) && $user->can($this->perm('submit')) && utils()->model_has_record_status($model) && $model->isDraft();
}
public function cancel(User $user, Model $model): bool
{
return ! $this->isImmutable($model) && $user->can($this->perm('cancel')) && utils()->model_has_record_status($model) && $model->isSubmitted();
}
public function reverse(User $user, Model $model): bool
{
return $user->can($this->perm('reverse')) && utils()->model_has_record_status($model) && $model->isSubmitted();
}
public function return(User $user, Model $model): bool
{
return $user->can($this->perm('return')) && utils()->model_has_record_status($model) && $model->isSubmitted();
}
public function restoreAny(User $user): bool
{
return false;
}
public function restore(User $user, Model $model): bool
{
return false;
}
public function forceDeleteAny(User $user): bool
{
return false;
}
public function forceDelete(User $user, Model $model): bool
{
return $this->delete($user, $model);
}
public function isImmutable(Model $record): bool
{
return $record->getAttribute('is_immutable') ?? false;
}
public function perm(string $prefix): string
{
return "{$prefix}_{$this->getSuffix()}";
}
}
|
# Ethical Pseudo ETF
## How to use?
### Stock
```bash
python3 stock.py --money=20000
```
returns integer stock counts to buy given investment money and existing stock positions.
### Crypto
```bash
python3 crypto.py --money=2000
```
returns US dollar amount for each coin. This is enough information as I use Robinhood for crypto investing which supports fractional share buying unlike Chase I use as the stock broakage account.
## What do I mean by "Pseudo ETF"?
I call this portfolio "Pseudo ETF" as I only trade integer stocks (no fractional share) and I do not sell stocks to match the index. So, I never match the perfect index but I buy towards it.
## What do I mean by "Ethical ETF"?
I try to avoid buying stocks from companies in sectors that do not match my ethical values. Even tough there are ETFs out there matching my ethics, the commision rates are typically at least 10 times more than that of VOO of Vanguard making them less attractive.
I also do not want to buy individual stocks without an automated criterion to avoid emotional trading. This repo is to standardize my stock selling strategy as I have more money to invest in.
## Investment Strategy
Goal is to buy stocks to get closer to the equilibrium point which is a market-cap weighted index of the stocks in the index.
Let say I have invested X USD so far to a subset of stocks in the index. Now, I have additional Y USD that I want to invest.
First, I compute the stock mapping for X+Y USD by computing the market cap of each company.
As an example it will return sth like the following, {'NVDA': 3, 'AAPL': 4}.
But, say my current positions are {'NVDA': 4, 'AAPL': 0}. This means I had more NVDA stocks than I supposed to.
Ideally, I buy "-1" NVDA and "4" Apple, stocks_to_buy={'NVDA': -1, 'AAPL': 4}.
But, this strategy involves no selling, so I won't be able to buy all AAPL stocks I need to.
To compute how many of them I can actually buy, I will sum over all stocks that are positive in stocks_to_buy. Let us call this sum Z>Y.
Then I multiply all the stocks to be bought (stocks_to_buy) with Y/Z.
## Positions Sheet
This is a Google sheet of "ethical" companies that I gathered mostly from top-10 publicly announced companies of the ETFs.
I keep my index tickers in a Google sheet but reading it via libraries like [gspread](https://docs.gspread.org/en/v6.0.0/) is an overkill as they require to create a Cloud project. Instead, I download the Google sheet into another local csv file.
## Reading stock positions.
I use a Chase brokage account. I download my positions from "Investments -> Positions -> Things you can do -> Export as -> CSV".
## Requirements
Install the following dependencies.
```bash
pip3 install yfinance
pip3 install pandas-datareader
pip3 install cryptocmd
```
|
import json
from asgiref.sync import sync_to_async
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import DatabaseSyncToAsync
from .models import Thread, ChatMessage
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("Websocket Connected!", event)
other = self.scope['url_route']['kwargs']['username']
me = self.scope['user']
thread, _ = await sync_to_async(Thread.objects.get_or_new)(me, other)
self.chatroom = f'thread_{thread.id}'
await self.channel_layer.group_add( self.chatroom, self.channel_name)
await self.send( { "type" : "websocket.accept" } )
async def websocket_receive(self, event):
print("Websocket Message Received!", event)
await self.channel_layer.group_send(
self.chatroom,
{
"type" : "send_msg",
"text": f'{event["text"]} by {self.scope["user"]}',
}
)
async def send_msg(self, event):
print('message', event)
await self.send({
"type" : "websocket.send",
"text" : event["text"]
})
async def websocket_disconnect(self, event):
print("Websocket Disconnected!", event)
|
<?php
declare(strict_types=1);
namespace KlarnaPayment\Components\Controller\Administration;
use KlarnaPayment\Components\Client\Client;
use KlarnaPayment\Components\Client\Hydrator\Request\CancelPayment\CancelPaymentRequestHydratorInterface;
use KlarnaPayment\Components\Client\Hydrator\Request\CreateCapture\CreateCaptureRequestHydratorInterface;
use KlarnaPayment\Components\Client\Hydrator\Request\CreateRefund\CreateRefundRequestHydratorInterface;
use KlarnaPayment\Components\Client\Hydrator\Request\ExtendAuthorization\ExtendAuthorizationRequestHydratorInterface;
use KlarnaPayment\Components\Client\Hydrator\Request\GetOrder\GetOrderRequestHydratorInterface;
use KlarnaPayment\Components\Client\Hydrator\Request\ReleaseRemainingAuthorization\ReleaseRemainingAuthorizationHydratorInterface;
use KlarnaPayment\Components\Client\Hydrator\Response\GetOrder\GetOrderResponseHydratorInterface;
use KlarnaPayment\Components\Client\Response\GetOrderResponse;
use KlarnaPayment\Components\DataAbstractionLayer\Entity\RequestLog\RequestLogEntity;
use Psr\Log\LoggerInterface;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStateHandler;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStates;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\Framework\Routing\Annotation\RouteScope;
use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
use Shopware\Core\System\StateMachine\Exception\IllegalTransitionException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
/**
* @RouteScope(scopes={"api"})
* @Route(defaults={"_routeScope": {"api"}})
*/
class OrderController extends AbstractController
{
/** @var Client */
private $client;
/** @var EntityRepository */
private $requestLogRepository;
/** @var GetOrderRequestHydratorInterface */
private $getOrderRequestHydrator;
/** @var GetOrderResponseHydratorInterface */
private $getOrderResponseHydrator;
/** @var CreateCaptureRequestHydratorInterface */
private $captureRequestHydrator;
/** @var CreateRefundRequestHydratorInterface */
private $refundRequestHydrator;
/** @var CancelPaymentRequestHydratorInterface */
private $cancelPaymentRequestHydrator;
/** @var ReleaseRemainingAuthorizationHydratorInterface */
private $remainingAuthorizationHydrator;
/** @var ExtendAuthorizationRequestHydratorInterface */
private $authorizationRequestHydrator;
/** @var OrderTransactionStateHandler */
private $stateHandler;
/** @var LoggerInterface */
private $logger;
/** @var EntityRepository */
private $orderTransactionRepository;
public function __construct(
Client $client,
EntityRepository $requestLogRepository,
GetOrderRequestHydratorInterface $getOrderRequestHydrator,
GetOrderResponseHydratorInterface $getOrderResponseHydrator,
CreateCaptureRequestHydratorInterface $captureRequestHydrator,
CreateRefundRequestHydratorInterface $refundRequestHydrator,
CancelPaymentRequestHydratorInterface $cancelPaymentRequestHydrator,
ReleaseRemainingAuthorizationHydratorInterface $remainingAuthorizationHydrator,
ExtendAuthorizationRequestHydratorInterface $authorizationRequestHydrator,
OrderTransactionStateHandler $stateHandler,
LoggerInterface $logger,
EntityRepository $orderTransactionRepository
) {
$this->client = $client;
$this->requestLogRepository = $requestLogRepository;
$this->captureRequestHydrator = $captureRequestHydrator;
$this->refundRequestHydrator = $refundRequestHydrator;
$this->getOrderRequestHydrator = $getOrderRequestHydrator;
$this->getOrderResponseHydrator = $getOrderResponseHydrator;
$this->cancelPaymentRequestHydrator = $cancelPaymentRequestHydrator;
$this->remainingAuthorizationHydrator = $remainingAuthorizationHydrator;
$this->authorizationRequestHydrator = $authorizationRequestHydrator;
$this->stateHandler = $stateHandler;
$this->logger = $logger;
$this->orderTransactionRepository = $orderTransactionRepository;
}
/**
* @Route("/api/_action/klarna_payment/fetch_order", name="api.action.klarna_payment.order.fetch", methods={"POST"})
* @Route("/api/v{version}/_action/klarna_payment/fetch_order", name="api.action.klarna_payment.order.fetch.legacy", methods={"POST"})
*/
public function fetchOrder(RequestDataBag $dataBag, Context $context): JsonResponse
{
$response = $this->getOrderResponse($dataBag, $context);
if (!$response) {
return new JsonResponse(['status' => 'error'], 400);
}
$history = $this->getHistory($dataBag->get('klarna_order_id'), $context);
return new JsonResponse(['order' => $response, 'transactionHistory' => $history], 200);
}
/**
* @Route("/api/_action/klarna_payment/capture_order", name="api.action.klarna_payment.order.capture", methods={"POST"})
* @Route("/api/v{version}/_action/klarna_payment/capture_order", name="api.action.klarna_payment.order.capture.legacy", methods={"POST"})
*/
public function captureOrder(RequestDataBag $dataBag, Context $context): JsonResponse
{
$request = $this->captureRequestHydrator->hydrate($dataBag, $context);
$response = $this->client->request($request, $context);
if ($response->getHttpStatus() !== 201) {
return new JsonResponse(['status' => 'error'], 400);
}
try {
if ($dataBag->get('complete')) {
if (method_exists($this->stateHandler, 'process') && method_exists($this->stateHandler, 'paid') && $this->isPartiallyPaid($dataBag->get('orderTransactionId'), $context)) {
// If the previous state is "paid_partially", "paid" is currently not allowed as direct transition, see https://github.com/shopwareLabs/SwagPayPal/blob/b63efb9/src/Util/PaymentStatusUtil.php#L79
$this->stateHandler->process($dataBag->get('orderTransactionId'), $context);
$this->stateHandler->paid($dataBag->get('orderTransactionId'), $context);
} else {
if (method_exists($this->stateHandler, 'paid')) {
$this->stateHandler->paid($dataBag->get('orderTransactionId'), $context);
} else {
/** @phpstan-ignore-next-line */
$this->stateHandler->pay($dataBag->get('orderTransactionId'), $context);
}
}
} else {
$this->stateHandler->payPartially($dataBag->get('orderTransactionId'), $context);
}
} catch (IllegalTransitionException $exception) {
// we can not ensure that the capture or capture partially status change is allowed
$this->logger->notice($exception->getMessage(), $exception->getParameters());
}
return new JsonResponse(['status' => 'success'], 200);
}
/**
* @Route("/api/_action/klarna_payment/refund_order", name="api.action.klarna_payment.order.refund", methods={"POST"})
* @Route("/api/v{version}/_action/klarna_payment/refund_order", name="api.action.klarna_payment.order.refund.legacy", methods={"POST"})
*/
public function refundOrder(RequestDataBag $dataBag, Context $context): JsonResponse
{
$request = $this->refundRequestHydrator->hydrate($dataBag, $context);
$response = $this->client->request($request, $context);
if ($response->getHttpStatus() !== 201) {
return new JsonResponse(['status' => 'error'], 400);
}
try {
if ($dataBag->get('complete')) {
$this->stateHandler->refund($dataBag->get('orderTransactionId'), $context);
} else {
$this->stateHandler->refundPartially($dataBag->get('orderTransactionId'), $context);
}
} catch (IllegalTransitionException $exception) {
// we can not ensure that the refund or refund partially status change is allowed
$this->logger->notice($exception->getMessage(), $exception->getParameters());
}
return new JsonResponse(['status' => 'success'], 200);
}
/**
* @Route("/api/_action/klarna_payment/extend_authorization", name="api.action.klarna_payment.extend.authorization", methods={"POST"})
* @Route("/api/v{version}/_action/klarna_payment/extend_authorization", name="api.action.klarna_payment.extend.authorization.legacy", methods={"POST"})
*/
public function extendAuthorizationTime(RequestDataBag $dataBag, Context $context): JsonResponse
{
$request = $this->authorizationRequestHydrator->hydrate($dataBag);
$response = $this->client->request($request, $context);
if ($response->getHttpStatus() !== 204) {
return new JsonResponse(['status' => 'error'], 400);
}
return new JsonResponse(['status' => 'success'], 200);
}
/**
* @Route("/api/_action/klarna_payment/cancel_payment", name="api.action.klarna_payment.cancel.payment", methods={"POST"})
* @Route("/api/v{version}/_action/klarna_payment/cancel_payment", name="api.action.klarna_payment.cancel.payment.legacy", methods={"POST"})
*/
public function cancelPayment(RequestDataBag $dataBag, Context $context): JsonResponse
{
$request = $this->cancelPaymentRequestHydrator->hydrate($dataBag);
$response = $this->client->request($request, $context);
if ($response->getHttpStatus() === 204) {
$this->stateHandler->cancel($dataBag->get('orderTransactionId'), $context);
return new JsonResponse(['success' => 'true'], 200);
}
return new JsonResponse(['success' => 'false'], 400);
}
/**
* @Route("/api/_action/klarna_payment/release_remaining_authorization", name="api.action.klarna_payment.release.remaining.authorization", methods={"POST"})
* @Route("/api/v{version}/_action/klarna_payment/release_remaining_authorization", name="api.action.klarna_payment.release.remaining.authorization.legacy", methods={"POST"})
*/
public function releaseRemainingAuthorization(RequestDataBag $dataBag, Context $context): JsonResponse
{
$request = $this->remainingAuthorizationHydrator->hydrate($dataBag);
$response = $this->client->request($request, $context);
if ($response->getHttpStatus() === 204) {
return new JsonResponse(['status' => 'success'], 200);
}
return new JsonResponse(['status' => 'error'], 400);
}
private function getOrderResponse(RequestDataBag $dataBag, Context $context): ?GetOrderResponse
{
$request = $this->getOrderRequestHydrator->hydrate($dataBag);
$response = $this->client->request($request, $context);
if ($response->getHttpStatus() !== 200) {
return null;
}
return $this->getOrderResponseHydrator->hydrate($response, $context);
}
/**
* @return array<int,mixed>
*/
private function getHistory(string $klarnaOrderId, Context $context): array
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('klarnaOrderId', $klarnaOrderId));
$criteria->addSorting(new FieldSorting('createdAt', FieldSorting::DESCENDING));
$repositoryResult = $this->requestLogRepository->search($criteria, $context);
$history = [];
/** @var RequestLogEntity $element */
foreach ($repositoryResult->getElements() as $element) {
if ($element->getCreatedAt() === null) {
continue;
}
$response = $element->getResponse();
$responseData = $response;
if (is_array($response)) {
if (array_key_exists('response', $response)) {
$responseData = $response['response'];
}
$error = array_key_exists('error_code', $responseData);
} else {
$error = false;
}
$history[] = [
'date' => $element->getCreatedAt()->format(DATE_ATOM),
'message' => $element->getCallType(),
'request' => json_encode($element->getRequest()),
'response' => json_encode($responseData),
'statusCode' => $response['httpStatus'] ?? null,
'error' => $error,
];
}
return $history;
}
private function isPartiallyPaid(string $orderTransactionId, Context $context): bool
{
$transaction = $this->getOrderTransaction($orderTransactionId, $context);
if ($transaction === null || $transaction->getStateMachineState() === null) {
return false;
}
return $transaction->getStateMachineState()->getTechnicalName() === OrderTransactionStates::STATE_PARTIALLY_PAID;
}
private function getOrderTransaction(string $orderTransactionId, Context $context): ?OrderTransactionEntity
{
return $this->orderTransactionRepository->search(new Criteria([$orderTransactionId]), $context)->getEntities()->first();
}
}
|
/**
* Reduce Function:
* Reduce is also a HOF for Arrays. Reduce also takes a function f as an argument.
* It goes one by one to every element in the array. Say the current element is arr[i], reduce
* will pass this element to the function f, and accumulate the result of further function calls with
* this particular result.
*/
const arr = [1, 2, 3, 4, 5, 6];
function sum(prevResult, currValue){
return prevResult + currValue;
}
const result = arr.reduce(sum);
console.log(result); // 21
function addPrices(prevResult, currValue){
console.log("prevResult: " + prevResult.price + " currValue: " + currValue.price);
let newPrice = prevResult.price + currValue.price;
return {price: newPrice};
}
let cart = [{price: 100000, name: "iPhone"}, {price: 50000, name: "backcover"}, {price: 2000, name: "tempered glass"}];
const totalPrice = cart.reduce(addPrices);
console.log(totalPrice.price);
|
import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import { IngresoService } from 'src/app/Servicios/ingreso.service';
var bootstrap : any;
@Component({
selector: 'app-ingresos',
templateUrl: './ingresos.component.html',
styleUrls: ['./ingresos.component.css']
})
export class IngresosComponent implements AfterViewInit {
@ViewChild('fileInput') fileInput: ElementRef | undefined;
selectedFile: File | undefined;
showSpinner = false;
showSecondModal = false;
constructor(private ingresoService:IngresoService) {}
onFileSelected(event: any) {
this.selectedFile = event.target.files[0];
}
onSubmit(event: Event) {
event.preventDefault();
if (this.selectedFile) {
this.showSpinner = true; // Muestra el spinner
const formData = new FormData();
formData.append('archivoExcel', this.selectedFile);
setTimeout(() => {
this.showSpinner = false;
this.ingresoService.CargarReporteExel(formData).subscribe(
data => {
this.showSecondModal = true;
console.log('Archivo cargado con éxito', data);
},
err=> {
console.error('Error al cargar el archivo', err);
}
);
},2000);
} else {
console.error('Debes seleccionar un archivo');
}
}
ngAfterViewInit(): void {
if (this.fileInput) {
this.fileInput.nativeElement.addEventListener('change', () => {
const label = document.querySelector('label[for="customFile"]');
if (label){
if (this.fileInput?.nativeElement.files.length > 0) {
label.textContent = this.fileInput?.nativeElement.files[0].name;
} else {
label.textContent = "Seleccionar Archivo";
}
}
});
}
}
}
|
import { WebPlugin } from '@capacitor/core';
import {
FacebookConfiguration,
FacebookCurrentAccessTokenResponse,
FacebookFriendsResponse,
FacebookGamingServices,
FacebookGetLoginStatusResponse,
FacebookGetProfileResponse,
FacebookLoginResponse,
} from './definitions';
declare interface Facebook {
init(
options: Partial<{
appId: string;
autoLogAppEvents: boolean;
xfbml: boolean;
version: string;
}>
): void;
login(handle: (response: any) => void, options?: { scope: string }): void;
logout(handle: (response: any) => void): void;
reauthorize(handle: (response: any) => void): void;
getLoginStatus(handle: (response: FacebookGetLoginStatusResponse) => void): void;
api<TResponse>(path: string, callback: (response: TResponse) => void): void;
api<TParams extends object, TResponse>(path: string, params: TParams, callback: (response: TResponse) => void): void;
api<TParams extends object, TResponse>(
path: string,
method: 'get' | 'post' | 'delete',
params: TParams,
callback: (response: TResponse) => void
): void;
}
declare var FB: Facebook;
declare global {
interface Window {
fbAsyncInit: Function;
}
}
export class FacebookLoginWeb extends WebPlugin implements FacebookGamingServices {
constructor() {
super({
name: 'FacebookLogin',
platforms: ['web'],
});
}
openGameRequest(): Promise<void> {
throw new Error('Method not implemented.');
}
shareLink(options: { url: string }): Promise<void> {
throw new Error('Method not implemented.');
}
openFriendFinder(): Promise<void> {
throw new Error('Method not implemented.');
}
initialize(options: Partial<FacebookConfiguration>): Promise<void> {
const defaultOptions = { version: 'v10.0' };
return new Promise((resolve, reject) => {
try {
return this.loadScript(options.locale).then(() => {
FB.init({ ...defaultOptions, ...options });
resolve();
});
} catch (err) {
reject(err);
}
});
}
private loadScript(locale: string | undefined): Promise<void> {
if (typeof document === 'undefined') {
return Promise.resolve();
}
const scriptId = 'fb';
const scriptEl = document?.getElementById(scriptId);
if (scriptEl) {
return Promise.resolve();
}
const head = document.getElementsByTagName('head')[0];
const script = document.createElement('script');
return new Promise<void>(resolve => {
script.defer = true;
script.async = true;
script.id = scriptId;
script.onload = () => {
resolve();
};
script.src = `https://connect.facebook.net/${locale ?? 'en_US'}/sdk.js`;
head.appendChild(script);
});
}
async login(options: { permissions: string[] }): Promise<FacebookLoginResponse> {
console.log('FacebookLoginWeb.login', options);
return new Promise<FacebookLoginResponse>((resolve, reject) => {
FB.login(
response => {
console.debug('FB.login', response);
if (response.status === 'connected') {
resolve({
accessToken: {
token: response.authResponse.accessToken,
},
});
} else {
reject({
accessToken: {
token: null,
},
});
}
},
{ scope: options.permissions.join(',') }
);
});
}
async logout(): Promise<void> {
return new Promise<void>(resolve => {
FB.logout(() => resolve());
});
}
async reauthorize(): Promise<FacebookLoginResponse> {
return new Promise<FacebookLoginResponse>(resolve => {
FB.reauthorize(it => resolve(it));
});
}
async getCurrentAccessToken(): Promise<FacebookCurrentAccessTokenResponse> {
return new Promise<FacebookCurrentAccessTokenResponse>((resolve, reject) => {
FB.getLoginStatus(response => {
if (response.status === 'connected') {
const result: FacebookCurrentAccessTokenResponse = {
accessToken: {
applicationId: undefined,
declinedPermissions: [],
expires: undefined,
isExpired: undefined,
lastRefresh: undefined,
permissions: [],
token: response.authResponse.accessToken,
userId: response.authResponse.userID,
},
};
resolve(result);
} else {
reject({
accessToken: {
token: null,
},
});
}
});
});
}
async getProfile<T extends object>(options: { fields: readonly string[] }): Promise<T> {
const fields = options.fields.join(',');
return new Promise<T>((resolve, reject) => {
FB.api<{ fields: string }, FacebookGetProfileResponse>('/me', { fields }, response => {
if (response.error) {
reject(response.error.message);
return;
}
resolve(<T>response);
});
});
}
getFriends(options: { fields: readonly string[] }): Promise<FacebookFriendsResponse> {
throw new Error('Method not implemented.');
}
getPicture<T extends object>(options: { fields: readonly string[] }): Promise<T> {
throw new Error('Method not implemented.');
}
getAppRequest<T extends object>(options: { fields: readonly string[] }): Promise<T> {
throw new Error('Method not implemented.');
}
getPermissions<T extends object>(options: { fields: readonly string[] }): Promise<T> {
throw new Error('Method not implemented.');
}
uploadPhoto(options: { base64string: string }): Promise<void> {
return Promise.resolve(undefined);
}
openContextChooser(): Promise<void> {
return Promise.resolve(undefined);
}
getCatalog(): Promise<any> {
return Promise.resolve(undefined);
}
deleteAppRequest(options: { requestId: String }): Promise<void> {
return Promise.resolve(undefined);
}
}
|
import React from "react";
import {
Card,
CardBody,
Input,
Label,
Row,
CustomInput,
Col,
Form,
UncontrolledDropdown,
DropdownMenu,
DropdownItem,
DropdownToggle,
Button,
} from "reactstrap";
import "../../../../assets/css/main.css";
import axiosConfig from "../../../../axiosConfig";
import { ContextLayout } from "../../../../utility/context/Layout";
import { AgGridReact } from "ag-grid-react";
import "ag-grid-community/dist/styles/ag-grid.css";
import { Eye, Trash2, ChevronDown, Edit } from "react-feather";
import { history } from "../../../../history";
import "../../../../assets/scss/plugins/tables/_agGridStyleOverride.scss";
import "../../../../assets/scss/pages/users.scss";
import swal from "sweetalert";
import AnalyticsDashboard from "../../../dashboard/analytics/AnalyticsDashboard";
import { Route, Link } from "react-router-dom";
class All extends React.Component {
state = {
rowData: [],
paginationPageSize: 20,
currenPageSize: "",
getPageSize: "",
info: true,
columnDefs: [
{
headerName: "S.No",
valueGetter: "node.rowIndex + 1",
field: "node.rowIndex + 1",
width: 70,
filter: true,
},
{
headerName: "Status",
field: "status",
filter: true,
width: 120,
cellRendererFramework: (params) => {
return params.value === "complete" ? (
<div className="badge badge-pill badge-success">Completed</div>
) : params.value === "pending" ? (
<div className="badge badge-pill badge-warning">
{params.data.status}
</div>
) : params.value === "delivery" ? (
<div className="badge badge-pill bg-primary">Delivered</div>
) : params.value === "canceled" ? (
<div className="badge badge-pill bg-danger">
{params.data.status}
</div>
) : params.value === "Order Placed" ? (
<div className="badge badge-pill bg-success">Order Placed</div>
) : null;
},
},
{
headerName: "Actions",
field: "sortorder",
field: "transactions",
width: 120,
cellRendererFramework: (params) => {
return (
<div className="actions cursor-pointer">
<Route
render={({ history }) => (
<Edit
className="mr-50"
size="25px"
color="blue"
onClick={() =>
history.push(
`/app/freshlist/order/EditOrder/${params.data._id}`
)
}
/>
)}
/>
<Route
render={() => (
<Trash2
className="mr-50"
size="25px"
color="red"
onClick={() => {
let selectedData = this.gridApi.getSelectedRows();
this.runthisfunction(params.data._id);
this.gridApi.updateRowData({ remove: selectedData });
}}
/>
)}
/>
</div>
);
},
},
{
headerName: "Order ID ",
field: "orderId",
filter: true,
resizable: true,
width: 150,
cellRendererFramework: (params) => {
return (
<div className="d-flex align-items-center cursor-pointer">
<div>
<span>{params.data.orderId}</span>
</div>
</div>
);
},
},
{
headerName: "Email",
field: "email",
filter: true,
resizable: true,
width: 200,
cellRendererFramework: (params) => {
return (
<div className="d-flex align-items-center cursor-pointer">
<div>
<span>{params.data.email}</span>
</div>
</div>
);
},
},
{
headerName: "Phone",
field: "phone",
filter: true,
resizable: true,
width: 200,
cellRendererFramework: (params) => {
return (
<div className="d-flex align-items-center cursor-pointer">
<div>
<span>{params.data.phone_no}</span>
</div>
</div>
);
},
},
// {
// headerName: "Order Date",
// field: "order_date",
// filter: "true",
// width: 200,
// cellRendererFramework: (params) => {
// return (
// <div className="d-flex align-items-center cursor-pointer">
// <div className="">
// <span>{params.data.order_date}</span>
// </div>
// </div>
// );
// },
// },
// {
// headerName: "Ordered",
// field: "ordered",
// filter: true,
// resizable: true,
// width: 80,
// cellRendererFramework: (params) => {
// return (
// <div className="d-flex align-items-center cursor-pointer">
// <div>
// <span>{params.data.orderd_from}</span>
// </div>
// </div>
// );
// },
// },
{
headerName: "Zone",
field: "zone",
filter: true,
resizable: true,
width: 120,
cellRendererFramework: (params) => {
return (
<div className="d-flex align-items-center cursor-pointer">
<div>
<span>{params.data.order_zone}</span>
</div>
</div>
);
},
},
{
headerName: "Delivery Address",
field: "delivery_address",
filter: true,
resizable: true,
width: 200,
cellRendererFramework: (params) => {
return (
<div className="d-flex align-items-center cursor-pointer">
<div>
<span>{params.data.delivery_add}</span>
</div>
</div>
);
},
},
// {
// headerName: "Assign Driver",
// field: "assign_driver",
// filter: true,
// resizable: true,
// width: 180,
// cellRendererFramework: (params) => {
// return (
// <div className="d-flex align-items-center cursor-pointer">
// <div>
// <span>{params.data.assing_drive}</span>
// </div>
// </div>
// );
// },
// },
// {
// headerName: "Permitions",
// field: "permitions",
// filter: true,
// width: 180,
// cellRendererFramework: (params) => {
// return (
// <CustomInput
// type="switch"
// className="mr-1"
// id="primary"
// name="primary"
// inline
// onChange={this.handleSwitchChange}
// ></CustomInput>
// );
// },
// },
// {
// headerName: "Status",
// field: "status",
// filter: true,
// width: 120,
// cellRendererFramework: (params) => {
// return params.value === "complete" ? (
// <div className="badge badge-pill badge-success">
// {params.data.status}
// </div>
// ) : params.value === "pending" ? (
// <div className="badge badge-pill badge-warning">
// {params.data.status}
// </div>
// ) : params.value === "delivery" ? (
// <div className="badge badge-pill bg-primary">
// {params.data.status}
// </div>
// ) : params.value === "canceled" ? (
// <div className="badge badge-pill bg-danger">
// {params.data.status}
// </div>
// ) : (
// "No Status"
// );
// },
// },
// {
// headerName: "Actions",
// field: "sortorder",
// field: "transactions",
// width: 120,
// cellRendererFramework: (params) => {
// return (
// <div className="actions cursor-pointer">
// <Route
// render={({ history }) => (
// <Edit
// className="mr-50"
// size="25px"
// color="blue"
// onClick={() =>
// history.push(
// `/app/freshlist/order/viewAll/${params.data._id}`
// )
// }
// />
// )}
// />
// <Route
// render={() => (
// <Trash2
// className="mr-50"
// size="25px"
// color="red"
// onClick={() => {
// let selectedData = this.gridApi.getSelectedRows();
// this.runthisfunction(params.data._id);
// this.gridApi.updateRowData({ remove: selectedData });
// }}
// />
// )}
// />
// </div>
// );
// },
// },
],
};
handleSwitchChange = () => {
return swal("Success!", "Submitted SuccessFull!", "success");
};
async componentDidMount() {
await axiosConfig.get("/admin/allorder_list").then((response) => {
let rowData = response.data.data;
this.setState({ rowData });
console.log(rowData);
});
}
async runthisfunction(id) {
await axiosConfig.delete(`/admin/del_order/${id}`).then((response) => {
swal("Row Deleted!", "SuccessFull Deleted!", "error");
console.log(response);
});
}
onGridReady = (params) => {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.setState({
currenPageSize: this.gridApi.paginationGetCurrentPage() + 1,
getPageSize: this.gridApi.paginationGetPageSize(),
totalPages: this.gridApi.paginationGetTotalPages(),
});
};
updateSearchQuery = (val) => {
this.gridApi.setQuickFilter(val);
};
filterSize = (val) => {
if (this.gridApi) {
this.gridApi.paginationSetPageSize(Number(val));
this.setState({
currenPageSize: val,
getPageSize: val,
});
}
};
onChangeHandler = (event) => {
this.setState({ selectedFile: event.target.files[0] });
this.setState({ selectedName: event.target.files[0].name });
console.log(event.target.files[0]);
};
onChangeHandler = (event) => {
this.setState({ selectedFile: event.target.files });
this.setState({ selectedName: event.target.files.name });
console.log(event.target.files);
};
changeHandler1 = (e) => {
this.setState({ status: e.target.value });
};
changeHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = (e) => {
e.preventDefault();
};
render() {
const { rowData, columnDefs, defaultColDef } = this.state;
return (
<Row className="app-user-list">
<Col sm="12">
<h2> Select Date Range</h2>
<Card>
<CardBody>
<Form className="m-1" onSubmit={this.submitHandler}>
<Row>
<Col lg="3" className="mb-2">
<Label>All</Label>
<Input
required
type="select"
name="bannertype"
placeholder=""
value={this.state.bannertype}
onChange={this.changeHandler}
>
<option value="select">--Select--</option>
<option value="All">All</option>
<option value="Painding">Painding</option>
<option value="Confirmed">Confirmed</option>
<option value="in_process">In Process</option>
<option value="out_for_delivery">Out for Delivery</option>
<option value="delivered">Delivered</option>
<option value="returned">Returned</option>
<option value="failed_to_deliver">
Failed to Deliver
</option>
</Input>
</Col>
<Col lg="3" className="mb-2">
<Label>Start Date</Label>
<Input
required
type="date"
name="bannertype"
placeholder=""
value={this.state.bannertype}
onChange={this.changeHandler}
></Input>
</Col>
<Col lg="3" className="mb-2">
<Label>End Date</Label>
<Input
required
type="date"
name="bannertype"
placeholder=""
value={this.state.bannertype}
onChange={this.changeHandler}
></Input>
</Col>
<Col lg="3" className="mb-2">
<Button.Ripple className="bt" color="primary" type="submit">
Show Data
</Button.Ripple>
</Col>
</Row>
</Form>
</CardBody>
</Card>
</Col>
<Col>
<AnalyticsDashboard />
</Col>
<Col sm="12">
<Card>
<Row className="m-2">
<Col>
<h1 col-sm-6 className="float-left">
All Order List
</h1>
</Col>
<Col>
<Route
render={({ history }) => (
<Button
className=" float-right"
color="primary"
onClick={() =>
history.push("/app/freshlist/order/addOrder")
}
>
Add Order
</Button>
)}
/>
</Col>
</Row>
<CardBody>
{this.state.rowData === null ? null : (
<div className="ag-theme-material w-100 my-2 ag-grid-table">
<div className="d-flex flex-wrap justify-content-between align-items-center">
<div className="mb-1">
<UncontrolledDropdown className="p-1 ag-dropdown">
<DropdownToggle tag="div">
{this.gridApi
? this.state.currenPageSize
: "" * this.state.getPageSize -
(this.state.getPageSize - 1)}
-
{this.state.rowData.length -
this.state.currenPageSize * this.state.getPageSize >
0
? this.state.currenPageSize * this.state.getPageSize
: this.state.rowData.length}
of {this.state.rowData.length}
<ChevronDown className="ml-50" size={15} />
</DropdownToggle>
<DropdownMenu right>
<DropdownItem
tag="div"
onClick={() => this.filterSize(20)}
>
20
</DropdownItem>
<DropdownItem
tag="div"
onClick={() => this.filterSize(50)}
>
50
</DropdownItem>
<DropdownItem
tag="div"
onClick={() => this.filterSize(100)}
>
100
</DropdownItem>
<DropdownItem
tag="div"
onClick={() => this.filterSize(134)}
>
134
</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
</div>
<div className="d-flex flex-wrap justify-content-between mb-1">
<div className="table-input mr-1">
<Input
placeholder="Hub Name"
onChange={(e) =>
this.updateSearchQuery(e.target.value)
}
value={this.state.value}
/>
</div>
<div className="table-input mr-1">
<Input
placeholder="Order Id"
onChange={(e) =>
this.updateSearchQuery(e.target.value)
}
value={this.state.value}
/>
</div>
<div className="table-input mr-1">
<Input
placeholder="Phone Number"
onChange={(e) =>
this.updateSearchQuery(e.target.value)
}
value={this.state.value}
/>
</div>
<div className="table-input mr-1">
<Input
placeholder="Enter Email"
onChange={(e) =>
this.updateSearchQuery(e.target.value)
}
value={this.state.value}
/>
</div>
<div className="export-btn">
<Button.Ripple
color="primary"
onClick={() => this.gridApi.exportDataAsCsv()}
>
Export as CSV
</Button.Ripple>
</div>
</div>
</div>
<ContextLayout.Consumer>
{(context) => (
<AgGridReact
gridOptions={{}}
rowSelection="multiple"
defaultColDef={defaultColDef}
columnDefs={columnDefs}
rowData={rowData}
onGridReady={this.onGridReady}
colResizeDefault={"shift"}
animateRows={true}
floatingFilter={false}
pagination={true}
paginationPageSize={this.state.paginationPageSize}
pivotPanelShow="always"
enableRtl={context.state.direction === "rtl"}
/>
)}
</ContextLayout.Consumer>
</div>
)}
</CardBody>
</Card>
</Col>
</Row>
);
}
}
export default All;
|
import { IsNotEmpty, IsNumber, IsString, ValidateNested } from "class-validator";
import { CriaUsuarioDto } from "src/usuarios/dtos/cria-usuario.dto";
export class CriaEnderecoDto {
@IsNumber()
@IsNotEmpty()
readonly cep: number;
@IsNotEmpty()
@IsString()
readonly logradouro: string;
@IsNumber()
@IsNotEmpty()
readonly numero: number;
@IsNotEmpty()
@IsString()
readonly bairro: string;
@IsNotEmpty()
@IsString()
readonly cidade: string;
@IsNotEmpty()
@IsString()
readonly estado: string;
readonly complemento: string;
}
|
package com.group_finity.mascot.action;
import com.group_finity.mascot.VShimejiApplication;
import com.group_finity.mascot.animation.Animation;
import com.group_finity.mascot.environment.Area;
import com.group_finity.mascot.exception.LostGroundException;
import com.group_finity.mascot.exception.VariableException;
import com.group_finity.mascot.script.VariableMap;
import java.awt.*;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Action of walking with a window.
*
* @author Yuki Yamada of <a href="http://www.group-finity.com/Shimeji/">Group Finity</a>
* @author Shimeji-ee Group
*/
public class WalkWithIE extends Move {
private static final Logger log = Logger.getLogger(WalkWithIE.class.getName());
public static final String PARAMETER_IEOFFSETX = "IeOffsetX";
private static final int DEFAULT_IEOFFSETX = 0;
public static final String PARAMETER_IEOFFSETY = "IeOffsetY";
private static final int DEFAULT_IEOFFSETY = 0;
// private double scaling;
public WalkWithIE(ResourceBundle schema, final List<Animation> animations, final VariableMap context) {
super(schema, animations, context);
}
/* @Override
public void init(final Mascot mascot) throws VariableException {
super.init(mascot);
scaling = Double.parseDouble(Main.getInstance().getProperties().getProperty("Scaling", "1.0"));
} */
@Override
public boolean hasNext() throws VariableException {
if (!Boolean.parseBoolean(VShimejiApplication.getInstance().getProperties().getProperty("Throwing", "true"))) {
return false;
}
return super.hasNext();
}
@Override
protected void tick() throws LostGroundException, VariableException {
final Area activeIE = getEnvironment().getActiveIE();
if (!activeIE.isVisible()) {
log.log(Level.INFO, "IE was hidden ({0}, {1})", new Object[]{getMascot(), this});
throw new LostGroundException();
}
// Can't use scaling here yet because it doesn't work for scales other than 1; the Shimejis will just release the window immediately.
// final int offsetX = (int) Math.round(getIEOffsetX() * scaling);
// final int offsetY = (int) Math.round(getIEOffsetY() * scaling);
final int offsetX = getIEOffsetX();
final int offsetY = getIEOffsetY();
if (getMascot().isLookRight()) {
if (getMascot().getAnchor().x - offsetX != activeIE.getLeft()
|| getMascot().getAnchor().y + offsetY != activeIE.getBottom()) {
log.log(Level.INFO, "Lost ground ({0}, {1})", new Object[]{getMascot(), this});
throw new LostGroundException();
}
} else {
if (getMascot().getAnchor().x + offsetX != activeIE.getRight()
|| getMascot().getAnchor().y + offsetY != activeIE.getBottom()) {
log.log(Level.INFO, "Lost ground ({0}, {1})", new Object[]{getMascot(), this});
throw new LostGroundException();
}
}
super.tick();
if (activeIE.isVisible()) {
if (getMascot().isLookRight()) {
getEnvironment().moveActiveIE(new Point(getMascot().getAnchor().x - offsetX, getMascot().getAnchor().y
+ offsetY - activeIE.getHeight()));
} else {
getEnvironment().moveActiveIE(new Point(getMascot().getAnchor().x + offsetX - activeIE.getWidth(),
getMascot().getAnchor().y + offsetY - activeIE.getHeight()));
}
}
}
private int getIEOffsetX() throws VariableException {
return eval(getSchema().getString(PARAMETER_IEOFFSETX), Number.class, DEFAULT_IEOFFSETX).intValue();
}
private int getIEOffsetY() throws VariableException {
return eval(getSchema().getString(PARAMETER_IEOFFSETY), Number.class, DEFAULT_IEOFFSETY).intValue();
}
}
|
# 夏洛克和字谜的有效解决方案
> 原文:<https://blog.devgenius.io/efficient-solution-to-sherlock-and-anagrams-hackerrank-48c0cb3efad3?source=collection_archive---------2----------------------->
# 问题陈述
我将讨论一个**不同的**和更**高效的**解决方案来应对[这次](https://www.hackerrank.com/challenges/sherlock-and-anagrams)黑客排名挑战。问题陈述如下:
> 如果一个字符串的字母可以重新排列形成另一个字符串,则两个字符串是彼此的 [*变位词*](http://en.wikipedia.org/wiki/Anagram) 。给定一个字符串,找出该字符串中互为变位词的子字符串对的数量。
在继续阅读这篇文章之前,如果你还没有解决它,我建议你自己解决它。说完了,我们开始吧!
# 通用解决方案
常见的解决方法是对字符串中的所有子串进行排序,存储每个排序后的子串出现的次数,对每个排序后的子串出现的所有组合数 C( *count* ,2)求和(每个子串出现的次数命名为 *count* )。更准确地说,该算法如下所示:

常见的 O(n log(n))算法。s 是字符串
算法复杂度 **O(n log(n))** 因为获取所有子串需要 O(n)时间,对每个子串排序需要 O(n log(n))。因为输入只包含 ASCII 字符,所以我们可以通过使用计数排序将总运行时间提高到 **O(n )** 。然而,**我们可以进一步改进它。**
首先,我们来分析一下为什么上面的算法行得通。
1. 我们获得所有的子串,不管它们是不是字谜。
2. 我们计算其中哪些是字谜。回想一下,如果一个子串的字母可以重新排列形成另一个子串,则两个子串 s1 和 s2 是彼此的变位词。因此,为了判断 s1 和 s2 是否是变位词,我们对 s1 和 s2 进行排序,如果它们相等,那么可以说它们是变位词,因为要将 s1 转换为 s2,我们可以对 s1 进行排序,然后以相反的顺序执行用于对 s2 进行排序的步骤。
3. 我们被要求提供互为变位词的子串对的数量。这就是为什么我们需要取组合 C( *count* ,2)=(*count*)(*count*-1)/2。如果你对那个等式有疑问,展开并简化 n!/[(n-r)!r!]对于 r=2,n= *计数。*
注意,子串并不存储在 hashmap 中,而是存储它的 hash(也就是键)(这就是它被称为 hashmap 的原因😯).因此,要判断两个子字符串是否是字谜,我们不是比较实际排序的子字符串,而是比较它们的哈希值。一个常见的散列函数由下式给出:

普通散列函数。p 和 q 是质数。s 是字符串,n 是它的长度。
几乎可以保证没有冲突(不同字符串的哈希相同)。但是,它仍然是可能的,例如,让 p 是 31 (java 使用这个值并且不执行模运算),那么 h('A@') = h('?') = 2049.在这种情况下,链表或 BST 被用在 hashmap 中,但是这不在本文的讨论范围之内(如果你想在 Java 运行`"@A".hashCode() == "?`".hashCode()`的话),因为在 Java 中指数从 n-1 开始下降。在[这篇文章](/assembly-by-example-compute-string-hash-part-2-loops-ba39de0ff6d6)中,简要讨论了为什么它更有表现力)
这里需要注意的重要一点是,哈希函数考虑了每个字符的**位置**和表示该字符的实际**值**(字节)。
# 拟议解决方案
如果我们有一个哈希函数**只考虑值**而不考虑位置,该怎么办?我们可以用它来确定两个字符串是否是字谜,因为如果它们有完全相同的字母(因此也有相同的散列),我们就知道有可能重新排列 s1 以获得 s2,反之亦然。
假设我们知道哈希函数是什么,那么我们可以使用下面更有效的 **O(n )** 算法。

高效的 O(n)算法
第 3 到 6 行计算长度为 1 的子串的所有哈希。
第 7 行到第 14 行计算长度为 2 到|s|-1 的子字符串的哈希,并记录它们的出现次数,就像前面的算法一样。请注意,长度为 *k >* 1 的子字符串的哈希是使用长度为 *k-1 的子字符串的哈希计算的。*因此,计算哈希在每次迭代中都要用到 **O(1)** 。
## 构造哈希函数
很好。但是现在我们怎么知道哪个是散列函数呢?让我们构建它。一个天真的方法是:

朴素哈希函数
尽管它保证所有字谜都有相同的散列,但很容易看出它会产生大量的冲突,例如 h(‘BBB’)= h(‘ABC’)= 294,这对我们显然是不利的。
为了解决这个问题,我想到了求和之间有一个巨大的差异,所以求和不太可能相似或相等(幸运的是,求和之间的差异会导致求和之间的差异更大)。
我们如何实现这一目标?好吧,让我们看看哪个算术运算符能帮助我们。
* 求和或减法:没用。添加一个常数不会有什么不同,我们刚刚看到简单的求和不好。
* 乘法或除法:我看不出这对我们有什么帮助。乘以一个常数是没有用的,乘以字符串中的其他字符(例如第一个字符或 k+1 字符)也没有用,因为这样做会导致依赖于字符位置的散列,我们不希望这样。
* 取幂:这可能是有用的。我们可以将子串中的每个字符取 p 的幂,反之亦然。这确实增加了被加数之间的差异。
所以现在建议的散列函数是:

冲突概率较小的哈希函数
现在,让我解释为什么这比另一个建议更好,并举例说明“被加数之间的方差”实际上是什么意思。下表认为 p 为 31,字符串采用 ASCII 编码。

使用简单散列函数的一些字符串的表摘要。方差列是指被加数之间的方差

使用精确散列函数的某些字符串的表摘要
从上面可以立即看到,对于改进的哈希函数,被加数之间的差异实际上更大,因此哈希之间的差异也更大,但它也有计算非常大的哈希的缺点。
为了解决这个问题,我们将利用输入字符串在 ASCII 编码中仅由从 *a* 到 *z* 的字母组成的事实,因此我们可以减去最小值 *a* 并得到一个较低的指数。因此,哈希函数最终成为

还值得注意的是,即使它不会产生大的哈希,被加数之间的方差也不会像以前那么大(p,p,p 之间的方差小于 p ⁰,p,p 的方差),这导致发生冲突的可能性更大,但我们可以通过选择更大的 p 值来减轻这种情况
另一个缺点是不能保证不会发生冲突,但我们可以通过增加 p 或者混合使用两种解决方案来减轻这种情况。例如,我们可以用不同的散列函数(具有不同的 p 值)计算两个散列,如果它们不同,那么对于一些子串,回退到 O(n log(n))解决方案,或者我们甚至可以使用两个散列作为关键字(像复合散列),这降低了冲突的概率。然而,我认为为 p 选择一个更大的值要容易得多。
# 密码
这两种算法在 Java 中的实现和比较如下:
正如您所看到的,我使用一个线程来执行每个解决方案,如果您想要精确的测量,这不是一个好主意(想想看,如果它们在不同的 CPU 内核中执行,并且它们有不同的工作负载,因此操作系统优先考虑一个线程,会发生什么)。但是,我不认为在这种情况下有多大关系。然而,您可以修改代码,使其按顺序执行。
另一个需要注意的重要事情是 BigInteger 的使用,它可能会增加一些开销,特别是在处理大数的时候。因此,我们可以说所提出的算法理论上具有 O(n)渐近行为,但实际的渐近行为是**几乎** O(n)。
如果您不能运行它,这是我为输入*ofeqjnqnxwiddhbuxhfwargwkikjqwyghpsyjxyrarcoachewnhxyqlvikfuuotifznqmzpjrxycnqktkryutpqvbgbgthfges*获得的结果

# 结论
尽管这是一个 HackerRank 挑战,显然没有任何实际应用,但思考如何构建有效的算法是很重要的,人们可以从这样的虚拟问题开始,分享比自己保留更酷,所以如果你找到更有效的哈希函数或进一步改进该算法的方法,请告诉我。
|
package com.thinkgem.jeesite.modules.wisdom.web.base;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.thinkgem.jeesite.common.crud.BaseCrudController;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.utils.ResultPage;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.Token;
import com.thinkgem.jeesite.modules.adopens.common.Result;
import com.thinkgem.jeesite.modules.card.utils.AESUtil;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.wisdom.dao.base.WisReceiveAddressDao;
import com.thinkgem.jeesite.modules.wisdom.entity.base.WisReceiveAddress;
import com.thinkgem.jeesite.modules.wisdom.service.base.WisReceiveAddressService;
import net.sf.json.JSONObject;
/**
* 收货地址信息Controller
*
* @author weekly
* @version 2019-09-19
*/
@Controller
@RequestMapping(value = "${adminPath}/wisdom/base/wisReceiveAddress")
public class WisReceiveAddressController
extends BaseCrudController<WisReceiveAddressService, WisReceiveAddressDao, WisReceiveAddress> {
String list = "modules/wisdom/base/wisReceiveAddressList"; // 表格页面
String form = "modules/wisdom/base/wisReceiveAddressForm"; // 表单页面
// 通用model
public void model(Model model) {
WisReceiveAddress wisReceiveAddress = new WisReceiveAddress();
model.addAttribute("rootUrl", "/wisdom/base/wisReceiveAddress"); // rootUrl 访问路径
model.addAttribute("tableName", wisReceiveAddress.getTableName()); // tableName 表名
}
// JSON对象字符串封装为对象
public WisReceiveAddress repJson(String json) {
return (WisReceiveAddress) JSONObject.toBean(toJsonObject(json), WisReceiveAddress.class);
}
@ModelAttribute
public WisReceiveAddress get(@RequestParam(required = false) String id) {
WisReceiveAddress entity = null;
if (StringUtils.isNotBlank(id)) {
entity = entityService.get(id);
}
if (entity == null) {
entity = new WisReceiveAddress();
}
return entity;
}
// 跳转到表格页面
@RequestMapping(value = { "show", "" })
public String list(Model model) {
model(model); // 通用model
return list;
}
// 获取模板分页信息
@RequestMapping(value = "/list")
@ResponseBody
@Token(save = true)
public ResultPage<List<WisReceiveAddress>> findAllList(WisReceiveAddress wisReceiveAddress) {
return findList(wisReceiveAddress);
}
// 跳转到修改或者查看页面
@RequestMapping(value = "getShow")
public String form(String id, String type, Model model) {
model(model); // 当前model方法
modelType(type, model);
logger.debug("type:" + type);
if (id != null && !"".equals(id)) {
model.addAttribute("wisReceiveAddress", entityService.get(id));
}
return form;
}
// 添加或修改信息
@RequestMapping(value = "save")
@ResponseBody
public void save(HttpServletResponse response, String json, String tableName) throws Exception {
WisReceiveAddress wisReceiveAddress = repJson(json);
if (null != wisReceiveAddress.getId() && !wisReceiveAddress.getId().equals("")) {
boolean bool = entityService.update(wisReceiveAddress);
if (bool) {
result.setCode(2);
result.setMsg("修改成功");
} else {
result.setCode(-2);
result.setMsg("修改失败");
}
} else {
boolean bool = entityService.insert(wisReceiveAddress);
if (bool) {
result.setCode(1);
result.setMsg("添加成功");
} else {
result.setCode(-1);
result.setMsg("添加失败");
}
}
response.getWriter().write(JsonMapper.getInstance().toJson(result));
}
/**
* 删除单个
*
* @param id
* @param tableName
* @param response
* @throws Exception
*/
@RequestMapping(value = "/delete", method = { RequestMethod.POST })
@ResponseBody
public void delete(String id, HttpServletResponse response) throws Exception {
Result result = new Result();
WisReceiveAddress wisReceiveAddress = new WisReceiveAddress();
wisReceiveAddress.setId(id);
if (null == id) {
result.setMsg("ID不能为空");
} else {
boolean bool = entityService.delete(wisReceiveAddress);
if (bool) {
result.setCode(1);
result.setMsg("删除成功!");
} else {
result.setCode(-1);
result.setMsg("删除失败!");
}
}
response.getWriter().write(JsonMapper.toJsonString(result));
}
/**
* 切换指定表指定主键指定字段的值
*
* @param colunms
* 字段名
* @param tableName
* 表名
* @param id
* 主键值
* @param value
* 切换值
* @param response
* @throws IOException
*
* @author weekly
* @version v19.07.29
*/
@RequestMapping(value = "/toggleTableColumns", method = { RequestMethod.POST })
@ResponseBody
public void toggleTableColumns(String colunms, String tableName, String id, String value,
HttpServletResponse response) throws IOException {
tableName = AESUtil.AESDncode("pulsation", tableName); // 解析主表名
// 传递表名、值、字段、关联ID
boolean bool = entityService.toggleTableColumns(colunms, tableName, id, value, UserUtils.getUser().getId(),
new Date());
if (bool) {
result.setCode(1);
result.setMsg("修改成功!");
result.setSuccess(true);
result.setData(1);
} else {
result.setCode(-1);
result.setMsg("修改失败");
result.setSuccess(false);
result.setData(-1);
}
response.getWriter().write(JsonMapper.toJsonString(result));
}
}
|
const CategoriaModel = require("../models/categoriaModel");
const MarcaModel = require("../models/marcaModel");
const ProdutoModel = require("../models/produtoModel");
const fs = require("fs");
class ProdutoController {
async listarView(req, res) {
let prod = new ProdutoModel();
let lista = await prod.listarProdutos();
res.render('produto/listar', {lista: lista});
}
async excluirProduto(req, res){
var ok = true;
if(req.body.codigo != "") {
let produto = new ProdutoModel();
ok = await produto.excluir(req.body.codigo);
}
else{
ok = false;
}
res.send({ok: ok});
}
async cadastrarProduto(req, res){
var ok = true;
if(req.body.codigo != "" && req.body.nome != "" &&
req.body.quantidade != "" && req.body.quantidade != '0' &&
req.body.marca != '0' && req.body.categoria != '0') {
let arquivo = req.file != null ? req.file.filename : null;
let produto = new ProdutoModel(0, req.body.codigo,
req.body.nome, req.body.quantidade,
req.body.categoria, req.body.marca, "", "", arquivo);
ok = await produto.gravar();
}
else{
ok = false;
}
res.send({ ok: ok })
}
async alterarView(req, res){
let produto = new ProdutoModel();
let marca = new MarcaModel();
let categoria = new CategoriaModel();
if(req.params.id != undefined && req.params.id != ""){
produto = await produto.buscarProduto(req.params.id);
}
let listaMarca = await marca.listarMarcas();
let listaCategoria = await categoria.listarCategorias();
res.render("produto/alterar", {produtoAlter: produto, listaMarcas: listaMarca, listaCategorias: listaCategoria});
}
async alterarProduto(req, res) {
var ok = true;
if(req.body.codigo != "" && req.body.nome != "" && req.body.quantidade != "" && req.body.quantidade != '0' && req.body.marca != '0' && req.body.categoria != '0') {
let produtoOld = new ProdutoModel();
produtoOld = await produtoOld.buscarProduto(req.body.id);
//apagar a imagem do produto se tiver uma nova imagem na alteração e se o antigo tiver imagem
let imagem = null
//se o file tiver preenchido, significa que a imagem será alterada
if(req.file != null) {
imagem = req.file.filename;
//se o meu produto já tiver uma imagem cadastrada, faço a deleção com o fs
if(produtoOld.possuiImagem) {
let imagemAntiga = produtoOld.imagem;
fs.unlinkSync(global.RAIZ_PROJETO + "/public/" + imagemAntiga);
}
}
else{ //se não, a imagem antiga deve ser mantida, mas apenas se houver
if(produtoOld.possuiImagem)
imagem = produtoOld.imagem.toString().split("/").pop();
}
let produto = new ProdutoModel(req.body.id, req.body.codigo, req.body.nome, req.body.quantidade, req.body.categoria, req.body.marca, "", "", imagem);
ok = await produto.gravar();
}
else{
ok = false;
}
res.send({ ok: ok })
}
async cadastroView(req, res) {
let listaMarcas = [];
let listaCategorias = [];
let marca = new MarcaModel();
listaMarcas = await marca.listarMarcas();
let categoria = new CategoriaModel();
listaCategorias = await categoria.listarCategorias();
res.render('produto/cadastro', { listaMarcas: listaMarcas, listaCategorias: listaCategorias });
}
}
module.exports = ProdutoController;
|
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
void display(struct node *head);
struct node *create_node(int key);
void insert_front(struct node **head,int key);
void insert_rear(struct node **head,int key);
void insert_pos(struct node **head,int key,int pos);
void delete_front(struct node **head);
void delete_rear(struct node **head);
void delete_ele(struct node **head,int key);
void insert_ordered(struct node **head,int key);
int main(){
int ch,key,pos;
struct node *head=NULL;
while(1){
display(head);
printf("\n1.Insert at front\n2.Insert at end\n3.Insert at pos\n4.Delete at front\n5.Delete rear\n6.Delete ele\n7.Ordered Insertion\n");
scanf("%d",&ch);
switch(ch){
case 1:
printf("\nEnter the element\n");
scanf("%d",&key);
insert_front(&head,key);
break;
case 2:
printf("\nEnter element\n");
scanf("%d",&key);
insert_rear(&head,key);
break;
case 3:
printf("\nEnter element and pos\n");
scanf("%d %d",&key,&pos);
insert_pos(&head,key,pos);
break;
case 4:
delete_front(&head);
break;
case 5:
delete_rear(&head);
break;
case 6:
printf("\nEnter element to be deleted\n");
scanf("%d",&key);
delete_ele(&head,key);
break;
case 7:
printf("\nEnter the key\n");
scanf("%d",&key);
insert_ordered(&head,key);
break;
}
}
}
void display(struct node *head){
if(head==NULL){
printf("\nEmpty list\n");
}
else{
struct node *p=head;
printf("\n");
while(p!=NULL){
printf("%d->",p->data);
p=p->next;
}
printf("\n");
}
}
struct node *create_node(int key){
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=key;
temp->next=NULL;
return temp;
}
void insert_front(struct node **head,int key){
struct node *temp=create_node(key);
if(*head==NULL){
*head=temp;
}
else{
temp->next=(*head);
*head=temp;
}
}
void insert_rear(struct node **head,int key){
struct node *temp = create_node(key);
if(*head==NULL){
*head=temp;
}
else{
struct node *p=*head;
while(p->next!=NULL){
p=p->next;
}
p->next=temp;
}
}
void insert_pos(struct node **head,int key,int pos){
struct node *temp=create_node(key);
int count=0;
if(*head==NULL&&pos==1){
*head=temp;
}
else{
struct node *p=*head;
struct node *prev=NULL;
count++;
while(count<pos){
prev=p;
p=p->next;
count++;
}
if(prev==NULL&&count<=pos&&p==NULL){
printf("\nInvalid position\n");
return;
}
else{
if(pos==1){
insert_front(head,key);
}
else{
temp->next=p;
prev->next=temp;
}
}
}
}
void insert_ordered(struct node **head,int key){
struct node *temp = create_node(key);
if(*head==NULL){
*head=temp;
}
else{
struct node *p = *head;
struct node *prev=NULL;
while(p!=NULL&&p->data<key){
prev=p;
p=p->next;
}
if(p==NULL){
prev->next=temp;
}
else if(prev==NULL){
temp->next=*head;
*head=temp;
}
else{
temp->next=prev->next;
prev->next=temp;
}
}
}
void delete_front(struct node **head){
if(*head==NULL){
printf("\nEmpty List\n");
return;
}
else{
struct node *p=*head;
(*head)=(*head)->next;
free(p);
}
}
void delete_rear(struct node **head){
if(*head==NULL){
printf("\nEmpty List\n");
return;
}
else{
struct node*p=*head;
struct node *prev=NULL;
while(p->next!=NULL){
prev=p;
p=p->next;
}
if(prev!=NULL){
prev->next=NULL;
free(p);
}
else{
*head=NULL;
free(p);
}
}
}
void delete_ele(struct node **head,int key){
if(*head==NULL){
printf("\nEmpty List\n");
return;
}
else{
struct node *p=*head;
struct node *prev=NULL;
while(p!=NULL&&p->data!=key){
prev=p;
p=p->next;
}
if(p==NULL){
printf("\nElement not found\n");
return;
}
else{
if(prev==NULL){
*head=(*head)->next;
free(p);
}
else{
prev->next=p->next;
free(p);
}
}
}
}
|
import { Suspense } from "react";
import { AO_API } from "@/constants";
import { HeadlineTemplate } from "@/components/headline-template";
import { ProvinceList } from "./province-list";
async function getData() {
const res = await fetch(`${AO_API}geography/provinces`);
if (!res.ok) {
throw new Error("Failed to fetch data");
}
return res.json();
}
export default async function Provinces() {
const data = await getData();
return (
<div className="max-w-4xl mx-auto p-8">
<HeadlineTemplate
title="Províncias"
description="Lista de todas as províncias de Angola."
/>
<Suspense fallback={<p>Carregando...</p>}>
<ProvinceList provinces={data} />
</Suspense>
</div>
);
}
|
import Foundation
import Glibc
// Solution @ Sergey Leschev, Belarusian State University
// 15. Caterpillar method. MinAbsSumOfTwo.
// Let A be a non-empty array consisting of N integers.
// The abs sum of two for a pair of indices (P, Q) is the absolute value |A[P] + A[Q]|, for 0 ≤ P ≤ Q < N.
// For example, the following array A:
// A[0] = 1
// A[1] = 4
// A[2] = -3
// has pairs of indices (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2).
// The abs sum of two for the pair (0, 0) is A[0] + A[0] = |1 + 1| = 2.
// The abs sum of two for the pair (0, 1) is A[0] + A[1] = |1 + 4| = 5.
// The abs sum of two for the pair (0, 2) is A[0] + A[2] = |1 + (−3)| = 2.
// The abs sum of two for the pair (1, 1) is A[1] + A[1] = |4 + 4| = 8.
// The abs sum of two for the pair (1, 2) is A[1] + A[2] = |4 + (−3)| = 1.
// The abs sum of two for the pair (2, 2) is A[2] + A[2] = |(−3) + (−3)| = 6.
// Write a function:
// class Solution { public int solution(int[] A); }
// that, given a non-empty array A consisting of N integers, returns the minimal abs sum of two for any pair of indices in this array.
// For example, given the following array A:
// A[0] = 1
// A[1] = 4
// A[2] = -3
// the function should return 1, as explained above.
// Given array A:
// A[0] = -8
// A[1] = 4
// A[2] = 5
// A[3] =-10
// A[4] = 3
// the function should return |(−8) + 5| = 3.
// Write an efficient algorithm for the following assumptions:
// N is an integer within the range [1..100,000];
// each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].
public func solution(_ A: inout [Int]) -> Int {
let sorted = A.sorted()
var minABS = Int.max
var p = 0
var q = sorted.count - 1
repeat {
let a = sorted[p]
var minDif = Int.max
var i = q
repeat {
let b = sorted[i]
let dif = abs(b + a)
if dif <= minDif {
minDif = dif
} else { break }
i -= 1
} while p <= i
q = i + 1
minABS = min(minABS, minDif)
p += 1
} while p <= q
return minABS
}
|
#!/usr/bin/env node
'use strict';
process.title = 'jm';
const fs = require('fs');
const program = require('commander');
const shell = require('shelljs/global');
const ora = require('ora');
const conventionalChangelog = require('conventional-changelog');
const { initProject, updateGhPages, genAuthor, genPage, getOptions } = require('../lib');
program
.usage('<command> [options]')
.version(require('../package.json').version)
.option('-c, --configure <path>', 'config file path')
program
.command('init')
.usage('<project-type> [project-name]')
.description('initialize project, you can choose the framework with AngularJS or Vue2')
.action(function () {
initProject()
});
program
.command('install')
.alias('i')
.description('Install Package')
.action(function () {
const spinner = ora('Installing Package...');
spinner.start();
exec('yarn install', {async: true}, function (code, stdout, stderr) {
spinner.stop();
console.log('Exit code:', code);
console.log('Program output:', stdout);
console.log('Program stderr:', stderr);
});
});
program
.command('dev')
.description('dev build')
.action(function () {
exec('yarn run dev');
});
program
.command('build')
.description('production build')
.action(function () {
exec('yarn run build');
});
program
.command('server')
.alias('s')
.description('production service')
.action(function () {
if(fs.existsSync('./server.js')) {
exec('node server');
} else {
console.log(` can't found server.js at root `)
}
});
program
.command('seed')
.description('publish seed')
.action(function () {
exec('jm jsdoc && jm changelog && jm author && jm site');
});
program
.command('jsdoc')
.alias('d')
.usage('-c <path>')
.description('generate jsdoc')
.action(function () {
if(program.config) {
require('jsdoc/jsdoc');
console.log(` jsdoc already created! `)
} else {
console.log('$ jm doc -c ./config/jm.config.json ')
console.log('The path to the configuration file. Default: ./config/jm.config.json')
}
// exec('jsdoc -c ' + confPath);
});
program
.command('changelog')
.alias('l')
.description('generate CHANGELOG.md')
.action(function() {
const fileName = typeof program.args[0] === 'string' ? program.args[0] : 'CHANGELOG.md';
conventionalChangelog({
preset: 'angular',
releaseCount: 0
})
.pipe(fs.createWriteStream(fileName)); // or any writable stream
console.log(` ${fileName} already created! `)
// exec('conventional-changelog -p angular -i CHANGELOG.md -s -r 0');
});
program
.command('author')
.alias('a')
.description('generate AUTHORS.md')
.action(function () {
const options = getOptions();
const fileName = typeof program.args[0] === 'string' ? program.args[0] : 'AUTHORS.md';
const exclude = options.authors && options.authors.exclude;
genAuthor(fileName, exclude);
});
program
.command('site')
.description('push gh-pages')
.action(function () {
const options = getOptions();
const list = options['gh-pages'].list;
updateGhPages(list);
});
program
.command('ng:page')
.description('generate new page')
.action(function () {
genPage()
});
/**
* help
*/
function help() {
program.parse(process.argv)
if (program.args.length < 1) {
return program.help()
}
}
help();
|
// --- Directions
// Write a function that accepts a positive number N.
// The function should console log a pyramid shape
// with N levels using the # character. Make sure the
// pyramid has spaces on both the left *and* right hand sides
// --- Examples
// pyramid(1)
// '#'
// pyramid(2)
// ' # '
// '###'
pyramid(20);
// ' # '
// ' ### '
// '#####'
function pyramid(n, row = 0, level = "") {
if (row === n) {
return;
}
if (level.length === 2 * n - 1) {
console.log(level);
return pyramid(n, row + 1);
}
const midpoint = Math.floor((2 * n - 1) / 2);
let add;
if (midpoint - row <= level.length && midpoint + row >= level.length) {
add = "#";
} else {
add = " ";
}
pyramid(n, row, level + add);
}
/* function pyramid(n) {
for (let i = 1; i <= n; i++) {
let str = " ".repeat(n - i);
let str2 = "#".repeat(i * 2 - 1);
console.log(str + str2 + str);
}
} */
/* function pyramid(n) {
// calculate the midpoint of the row
const midpoint = Math.floor((2 * n - 1) / 2);
for (let row = 0; row < n; row++) {
let level = "";
// number of columns is twice the number of rows minus one
for (let column = 0; column < 2 * n - 1; column++) {
if (midpoint - row <= column && midpoint + row >= column) {
level += "#";
} else {
level += " ";
}
}
console.log(level);
}
} */
module.exports = pyramid;
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import '../../../theme/theme.dart';
class AdminLaundry extends StatefulWidget {
@override
_AdminLaundryState createState() => _AdminLaundryState();
}
class _AdminLaundryState extends State<AdminLaundry> {
bool hasLaundry;
@override
void initState() {
hasLaundry = false;
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: darkerBlue,
title: Text("Add Student", style: lightHeading),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Has Laundry Plan:"),
Container(
padding: EdgeInsets.all(15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Yes",
),
Radio<bool>(
groupValue: hasLaundry,
value: true,
onChanged: (v) {
setState(() {
hasLaundry = v;
});
}),
Text(
"No",
),
Radio<bool>(
groupValue: hasLaundry,
value: false,
onChanged: (v) {
setState(() {
hasLaundry = v;
});
}),
],
),
),
],
),
Expanded(
child: Container(
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('student')
.where('laundryCheck', isEqualTo: hasLaundry)
.snapshots(),
builder: (ctx, opSnapshot) {
if (opSnapshot.connectionState == ConnectionState.waiting)
return Center(
child: CircularProgressIndicator(),
);
final reqDocs = opSnapshot.data.documents;
print('length ${reqDocs.length}');
return ListView.builder(
itemCount: reqDocs.length,
itemBuilder: (ctx, index) {
if (opSnapshot.hasData)
return StudentCard(
reqDoc: reqDocs[index],
laundryCheck: hasLaundry,
);
return Container(
height: 0,
);
},
);
},
),
),
),
],
),
);
}
}
class StudentCard extends StatefulWidget {
final dynamic reqDoc;
final bool laundryCheck;
StudentCard({this.reqDoc, this.laundryCheck});
@override
_StudentCardState createState() => _StudentCardState();
}
class _StudentCardState extends State<StudentCard> {
bool planType;
@override
void initState() {
planType = true;
planName = 30;
super.initState();
}
dynamic mentorFirestoreDB;
String bagID;
int planName;
final bagIDController = TextEditingController();
_buildBagID() {
return Padding(
padding: EdgeInsets.symmetric(vertical: 5),
child: TextFormField(
controller: bagIDController,
decoration:
InputDecoration(hintText: "W250", labelText: 'Enter Bag ID:'),
// ignore: missing_return
validator: (String value) {
if (value.isEmpty) {
return 'Field is required';
}
},
onSaved: (String value) {
bagID = value;
},
),
);
}
Widget _buildCycles() {
return Padding(
padding: EdgeInsets.symmetric(vertical: 5),
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"30 Cycles",
),
Radio<bool>(
groupValue: planType,
value: true,
onChanged: (v) {
setState(() {
planType = v;
planName = 30;
});
}),
Text(
"15 Cycles",
),
Radio<bool>(
groupValue: planType,
value: false,
onChanged: (v) {
setState(() {
planType = v;
planName = 15;
});
}),
],
);
}),
);
}
@override
Widget build(BuildContext context) {
final studentName = widget.reqDoc.get("studentName");
final courseName = widget.reqDoc.get("courseName");
final regNo = widget.reqDoc.get("registrationNumber");
final roomNumber = widget.reqDoc.get("roomNumber");
final block = widget.reqDoc.get("block");
final uid = widget.reqDoc.get("studentID");
return widget.laundryCheck == true
? Container(
padding: const EdgeInsets.all(10),
child: Container(
padding: const EdgeInsets.all(10),
child: Container(
width: double.infinity,
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(70),
topLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
),
),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children: [
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
children: [
Text(
'Student Name: ',
style: darkSmallTextBold,
// style: darkSmallTextBold,
),
Text(
'$studentName',
),
],
),
Row(
children: [
Text(
'Registration Number: ',
style: darkSmallTextBold,
// style: darkSmallTextBold,
),
Text(
'$regNo',
),
],
),
Row(
children: [
Text(
'Course Name: ',
style: darkSmallTextBold,
// style: darkSmallTextBold,
),
Text('$courseName'),
],
),
Row(
children: [
Text(
'Block-Room Number: ',
style: darkSmallTextBold,
// style: darkSmallTextBold,
),
Text(block + "-" + roomNumber),
],
),
// ignore: deprecated_member_use
],
),
Column(
children: [
GestureDetector(
child: MaterialButton(
onPressed: () {
_showRemoveDialog(studentName, uid);
},
child: Icon(Icons.remove_circle_outline),
)),
Text(
"Remove User",
style: TextStyle(fontSize: 13),
)
],
),
]),
),
),
)))
: Container(
padding: const EdgeInsets.all(10),
child: Container(
padding: const EdgeInsets.all(10),
child: Container(
width: double.infinity,
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(70),
topLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
),
),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children: [
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
children: [
Text(
'Student Name: ',
style: darkSmallTextBold,
// style: darkSmallTextBold,
),
Text(
'$studentName',
),
],
),
Row(
children: [
Text(
'Registration Number: ',
style: darkSmallTextBold,
// style: darkSmallTextBold,
),
Text(
'$regNo',
),
],
),
Row(
children: [
Text(
'Course Name: ',
style: darkSmallTextBold,
// style: darkSmallTextBold,
),
Text('$courseName'),
],
),
Row(
children: [
Text(
'Block-Room Number: ',
style: darkSmallTextBold,
// style: darkSmallTextBold,
),
Text(block + "-" + roomNumber),
],
),
// ignore: deprecated_member_use
],
),
Column(
children: [
GestureDetector(
child: MaterialButton(
onPressed: () {
_showApproveDialog(uid);
},
child: Icon(Icons.group_add),
)),
Text(
"Add User",
style: TextStyle(fontSize: 13),
)
],
),
]),
),
),
)));
}
Future<void> _showApproveDialog(String uid) async {
return showDialog<void>(
context: context,
barrierDismissible: true, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Add User'),
content: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SingleChildScrollView(
child: ListBody(
children: <Widget>[
_buildBagID(),
_buildCycles(),
],
),
);
}),
actions: <Widget>[
TextButton(
child: Text('Add'),
onPressed: () {
print(uid);
print(planName);
print(bagIDController.text);
setState(() {
FirebaseFirestore.instance
.collection('student')
.doc(uid)
.update({
"laundryCheck": true,
"Cycles": planName,
"laundryStatus": 'Active',
"bagID": bagIDController.text,
});
});
Navigator.of(context).pop();
},
),
],
);
},
);
}
Future<void> _showRemoveDialog(String uName, String uid) async {
return showDialog<void>(
context: context,
barrierDismissible: true, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Remove User'),
content: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text("Do You Want to Remove: $uName from Laundry Service")
],
),
);
}),
actions: <Widget>[
TextButton(
child: Text('Remove'),
onPressed: () {
setState(() {
FirebaseFirestore.instance
.collection('student')
.doc(uid)
.update({
"laundryCheck": false,
"Cycles": null,
"laundryStatus": 'Inactive',
"bagID": "",
});
});
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
|
<script lang="ts">
import type { PageData } from './$types';
import { base } from '$app/paths';
import { timeDelta, truncate } from '$lib/utils';
import { page } from '$app/stores';
export let data: PageData;
$: console.log('blogs', data.blogs);
</script>
<svelte:head>
<title>DMT Blog</title>
<meta name="description" content="A list of all my personal blogs" />
<meta property="og:url" content={$page.url.href} />
<meta property="og:title" content="Persnal Blogs | DMT" />
<meta property="og:image" content={$page.url.origin + base + '/favicon.png'} />
</svelte:head>
<div class="w-full h-full gap-4 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3">
{#each data.blogs as { title, pathname, cover, publishedAt }}
<a
href="{base}/{pathname}"
class="bg-gray-900 grid grid-cols-8 gap-4 relative rounded transition-all ease-in-out duration-300 group hover:md:scale-105"
>
{#if cover}
<div class="col-span-2">
<img class="rounded object-cover w-full aspect-square" src="{base}/file/{cover}" alt="" />
</div>
{/if}
<div class="col-span-6 flex flex-col justify-between relative">
<p class="text-base w-full block ">
<span class="hidden md:block group-hover:md:hidden">{truncate(title, 70)}</span>
<span class="md:hidden group-hover:underline">{title}</span>
<span class="hidden group-hover:xl:block group-hover:underline">{truncate(title, 100)}</span>
<span class="hidden group-hover:lg:block group-hover:xl:hidden group-hover:underline">{truncate(title, 120)}</span>
<!-- <span
class="group-hover:underline hidden group-hover:block group-hover:shadow-lg group-hover:bg-gray-900 group-hover:absolute group-hover:top-0 group-hover:left-0"
>{title}</span
> -->
</p>
<p class="group-hover:md:hidden text-xs py-3">Published: <span use:timeDelta={{ date: publishedAt }} /></p>
</div>
</a>
{/each}
{#if !data.blogs.length}
<p class=" text-4xl">Zero blogs. Start writing buddy!</p>
{/if}
</div>
<style>
/* a {
background-color: var(--zeta-green);
color: green;
} */
/* .sh{
filter: drop-shadow(0 15px 13px rgba(255, 255, 255, 0.04)) drop-shadow(0 8px 5px rgb(255 255 255 / 0.1));
} */
</style>
|
import Link from "@docusaurus/Link";
import { ShowcaseSpotlight } from "@site/src/types/showcase";
import styles from "./index.module.scss";
export default function Spotlight({
title,
description,
img,
url
}: ShowcaseSpotlight): JSX.Element {
return (
<Link href={url} target="_blank" rel="noreferrer noopener nofollow">
<article className={`button button--juno ${styles.card}`}>
<div className={styles.imgContainer}>
<img
src={img}
loading="lazy"
className={styles.img}
role="presentation"
alt={`${title} banner`}
/>
</div>
<div className={styles.content}>
<h4>{title}</h4>
<p>{description}</p>
</div>
</article>
</Link>
);
}
|
import React, { useCallback, useMemo } from "react";
import styled from "styled-components";
import avatar from "../../../public/images/avatar.png";
import { hostUrl } from "../../api";
import { MessageIcon } from "../SVG";
import Image from "next/image";
const StyledWrapper = styled.div`
position: relative;
text-align: center;
flex-shrink: 0;
text-decoration: none;
width: 60px;
cursor: pointer;
`;
const StyledPhoto = styled(Image)`
height: 51px;
width: 51px;
object-fit: cover;
border-radius: 5px;
`;
const StyledName = styled.p`
position: relative;
background: #2a9b9f;
border-radius: 5px;
font-weight: 300;
font-size: 10px;
line-height: 17px;
text-align: center;
letter-spacing: 0.01em;
color: #ffffff;
margin-top: -14px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const StyledBtn = styled.button`
background-color: #fff;
padding: 0;
border: 0;
position: absolute;
top: 1px;
inset-inline-end: 0;
cursor: pointer;
padding: 2px;
border-radius: 3px;
`;
interface IProps {
name: string;
imgUrl?: string;
onClick: () => void;
onMessage?: () => void;
}
const UserThumb = React.memo(
({ name, imgUrl, onClick, onMessage }: IProps) => {
const avatarSrc = useMemo(() => {
if (!imgUrl) return avatar;
return `${hostUrl}${imgUrl}`;
}, [imgUrl]);
const handleMessage = useCallback(
(e: any) => {
e.stopPropagation();
if (onMessage) onMessage();
},
[onMessage]
);
return (
<StyledWrapper onClick={onClick}>
<StyledPhoto src={avatarSrc} height={51} width={51} alt="user photo" />
<StyledName>{name}</StyledName>
{onMessage && (
<StyledBtn onClick={handleMessage}>
<MessageIcon />
</StyledBtn>
)}
</StyledWrapper>
);
}
);
export default UserThumb;
|
<script setup>
import { onMounted, ref, watch } from 'vue';
import DangerModal from '../modal/DangerModal.vue';
import use_department_head from '@/composables/DepartmentHead.js';
import useDepartment from '@/composables/Department.js';
import { Notify, refreshTable, getErrorText } from "@/newShared";
import {
generalErrorMsg,
generalSuccessMsg,
errors
} from "@/axiosClient";
import CustomPasswordInput from '../form/CustomPasswordInput.vue';
const { get_department_heads,
store_department_head,
update_department_head,
destroy_department_head,
department_heads, } = use_department_head();
const { get_departments,
departments, } = useDepartment();
const department_head = {
'id': '',
'first_name': '',
'last_name': '',
'email': '',
'password': '',
'password_confirmation': '',
'department_id': '',
"department": {
"name": '',
"short_cut": '',
}
}
const current_department_head = ref(_.cloneDeep(department_head))
const is_current_department_head_edited = ref(false)
let principleTable = null;
$(document).on('click', 'tr button', async (e) => {
let department_head_id = e.currentTarget.getAttribute('department_head_id')
let button_role = e.currentTarget.getAttribute('button-role')
if (button_role == "edit") {
is_current_department_head_edited.value = true;
window.scrollTo(0, 0);
}
if (department_head_id != undefined) {
current_department_head.value = department_heads.value.find(st => st.id == department_head_id);
}
});
const principleColumns =
[
{
'data': 'null', render: function (data, type, row) {
return row.first_name + " " + row.last_name;
}
},
{ 'data': 'email' },
{ 'data': 'department.name' },
{ 'data': 'department.short_cut' },
{
data: null,
render: function (data, type, row) {
return ` <button department_head_id='${data.id}'button-role="edit" type="button" class="btn btn-warning btn-sm me-2" ><i class="mdi mdi-wrench"></i></button>
<button button_type="delete" department_head_id='${data.id}' type="button" class="btn btn-danger btn-sm " data-bs-toggle="modal"
data-bs-target="#fill-danger-modal"><i
class="mdi mdi-window-close"></i></button>`;
}
},
];
const save_department_head = async () => {
if (current_department_head.value.id == "") {
await store_department_head(current_department_head.value)
} else {
await update_department_head(current_department_head.value.id,current_department_head.value)
}
Notify(generalSuccessMsg.value, generalErrorMsg.value)
if (generalErrorMsg.value == '') {
await get_department_heads();
refreshTable(principleTable, department_heads.value)
is_current_department_head_edited.value = false;
current_department_head.value = _.cloneDeep(department_head)
}
}
const delete_department_head = async (department_head) => {
await destroy_department_head(department_head.id)
Notify(generalSuccessMsg.value, generalErrorMsg.value)
if (generalSuccessMsg.value != '') {
await get_department_heads()
refreshTable(principleTable, department_heads.value)
}
current_department_head.value = _.cloneDeep(department_head)
}
onMounted(async () => {
await get_department_heads()
await get_departments()
import('@/assets/js/vendor/jquery.dataTables.min.js').then(() => {
import('@/assets/js/vendor/dataTables.bootstrap5.js').then(() => {
import('@/assets/js/vendor/dataTables.responsive.min.js').then(() => {
import('@/assets/js/vendor/responsive.bootstrap5.min.js').then(() => {
principleTable = $("#scroll-horizontal-datatable").DataTable({
scrollX: !0,
language: {
paginate: {
previous: "<i class='mdi mdi-chevron-left'>",
next: "<i class='mdi mdi-chevron-right'>"
}
},
drawCallback: function () {
$(".dataTables_paginate > .pagination").addClass("pagination-rounded")
},
data: department_heads.value,
columns: principleColumns
});
});
});
});
});
});
</script>
<template>
<div class="row">
<div class="col-12">
<div class="page-title-box">
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item active">Manage Department heads Accounts</li>
</ol>
</div>
<h4 class="page-title">Manage Department Heads</h4>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="header-title">department head Information</h4>
<p class="text-muted font-14">
Add a New department_head
</p>
<form class="row">
<div class="col-lg-6">
<FloatingInput v-model="current_department_head.first_name"
:errorText="getErrorText(errors, 'first_name')"
:showError="errors.hasOwnProperty('first_name')" label="First Name"
placeholder="Enter First Name" />
</div>
<div class="col-lg-6">
<FloatingInput v-model="current_department_head.last_name"
:errorText="getErrorText(errors, 'last_name')"
:showError="errors.hasOwnProperty('last_name')" label="Last Name"
placeholder="Enter Last Name" />
</div>
<div class="col-lg-6">
<FloatingInput v-model="current_department_head.email"
:errorText="getErrorText(errors, 'email')" :showError="errors.hasOwnProperty('email')"
label="Department Head Email" placeholder="Enter Department Head Email" />
</div>
<div class="col-lg-6 ">
<SelectInput propertyOfValue="id" property-of-show="name" placeholder="Select Department"
:floatingTheme="true" v-model="current_department_head.department_id"
:errorText="getErrorText(errors, 'department_id')"
:showError="errors.hasOwnProperty('department_id')" label="Select Department"
:options="departments">
</SelectInput>
</div>
<template v-if="!is_current_department_head_edited">
<div class="col-lg-6 ">
<CustomPasswordInput v-model="current_department_head.password"
:errorText="getErrorText(errors, 'password')" placeholder="Enter Passord Again"
label="Password" :showError="errors.hasOwnProperty('password')" />
</div>
<div class="col-lg-6 ">
<CustomPasswordInput v-model="current_department_head.password_confirmation"
:errorText="getErrorText(errors, 'password_confirmation')"
placeholder="Enter a Strong Password" label="Confirm Password"
:showError="errors.hasOwnProperty('password_confirmation')" />
</div>
</template>
</form>
<div>
<button @click="save_department_head" class="btn btn-primary">Submit</button>
</div>
</div> <!-- end card-body -->
</div> <!-- end card -->
</div><!-- end col -->
</div><!-- end row -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="header-title">All department heads</h4>
<p class="text-muted font-14">
Here is a list of all department_heads in the University
</p>
<table id="scroll-horizontal-datatable" class="table table-hover table-bordered w-100 nowrap ">
<thead>
<tr>
<th>Full Name</th>
<th>Email</th>
<th>Department name</th>
<th>Department short cut</th>
<th data-orderable="false">Action</th>
</tr>
</thead>
</table>
</div> <!-- end card body-->
</div> <!-- end card -->
</div><!-- end col-->
</div> <!-- end row-->
<DangerModal modal_heading="Delete Department Head">
<template v-slot:body>
Are you sure you want to delete department_head <b>{{ current_department_head.first_name }} {{
current_department_head.last_name }} </b>
</template>
<template v-slot:buttons>
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
<button @click="delete_department_head(current_department_head)" type="button" class="btn btn-outline-light"
data-bs-dismiss="modal">Delete</button> </template>
</DangerModal>
</template>
<style>
@import "@/assets/css/vendor/dataTables.bootstrap5.css";
@import "@/assets/css/vendor/responsive.bootstrap5.css";
</style>
|
package com.example.nearbymetro.di
import com.example.nearbymetro.remote.api.MapsApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
@Provides
@Singleton
fun getRetrofitInstance(): Retrofit {
return Retrofit
.Builder()
.baseUrl("")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Provides
@Singleton
fun getMapsApi(retrofit: Retrofit): MapsApi {
return retrofit.create(MapsApi::class.java)
}
}
|
import React from "react";
import {
CardTitle,
CardDescription,
CardHeader,
CardFooter,
Card,
CardContent,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
export function DashboardSummary() {
return (
<div className="grid gap-4 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-2 xl:grid-cols-4">
<Card className="sm:col-span-2" x-chunk="dashboard-05-chunk-0">
<CardHeader className="pb-3">
<CardTitle>Your Deployments</CardTitle>
<CardDescription className="max-w-lg text-balance leading-relaxed">
Introducing Our Dynamic Orders Dashboard for Seamless
Management and Insightful Analysis.
</CardDescription>
</CardHeader>
<CardFooter>
<Button>Create New Deployment</Button>
</CardFooter>
</Card>
<Card x-chunk="dashboard-05-chunk-1">
<CardHeader className="pb-2">
<CardDescription>This Week</CardDescription>
<CardTitle className="text-4xl">16 Deployments</CardTitle>
</CardHeader>
<CardContent>
<div className="text-xs text-muted-foreground">
+25% from last week
</div>
</CardContent>
<CardFooter>
<Progress aria-label="25% increase" value={25} />
</CardFooter>
</Card>
<Card x-chunk="dashboard-05-chunk-2">
<CardHeader className="pb-2">
<CardDescription>This Month</CardDescription>
<CardTitle className="text-4xl">50 Deployments</CardTitle>
</CardHeader>
<CardContent>
<div className="text-xs text-muted-foreground">
+10% from last month
</div>
</CardContent>
<CardFooter>
<Progress aria-label="12% increase" value={12} />
</CardFooter>
</Card>
</div>
);
}
|
@extends('layouts.template')
@section('content')
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Courses</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item active">Courses</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<!-- Main content -->
<section class="content">
@if (session('success'))
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="alert alert-success alert-dismissible fade show text-center" role="alert">
{{ session('success') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
</div>
@endif
<a href="{{ url('keluarga/create') }}" class="btn btn-sm btn-success my-2">
<i class="fas fa-plus"></i> Add Data
</a>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">No</th>
<th scope="col">Nama</th>
<th scope="col">Alamat</th>
<th scope="col">NIK</th>
<th scope="col">Agama</th>
<th scope="col">Pendidikan</th>
<th scope="col">Pekerjaan</th>
<th scope="col">Hubungan</th>
</tr>
</thead>
<tbody>
@php
$id = 1;
@endphp
@if ($keluarga->count() > 0)
@foreach ($keluarga as $item)
<tr>
<th scope="row">{{ $id++ }}</th>
<td>{{ $item->nama_wali }}</td>
<td>{{ $item->alamat_wali }}</td>
<td>{{ $item->nik_wali }}</td>
<td>{{ $item->agama }}</td>
<td>{{ $item->pendidikan_wali }}</td>
<td>{{ $item->pekerjaan_wali }}</td>
<td>{{ $item->hubungan }}</td>
<td>
<!-- Bikin tombol edit dan delete -->
<a href="{{ url('/keluarga/' . $item->id_keluarga . '/edit') }}"
class="btn btn-sm btn-warning"> <i class="fas fa-edit"></i> Edit </a>
<form method="POST" action="{{ url('/keluarga/' . $item->id_keluarga) }}">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-sm btn-danger"> <i class="fas fa-trash"></i>
Delete</button>
</form>
</td>
</tr>
@endforeach
@else
<tr>
<td colspan="6" class="text-center">No Data Available</td>
</tr>
@endif
</tbody>
</table>
</section>
<!-- /.content -->
</div>
@endsection
|
---
layout: post
title: "[파이썬] 모듈과 외부 라이브러리의 활용"
description: " "
date: 2023-09-01
tags: [python]
comments: true
share: true
---
파이썬은 많은 기능과 유용한 도구를 제공하는 언어입니다. 이러한 기능을 모두 파악하고 구현하는 것은 어려운 일이 될 수 있습니다. 다행히도 파이썬은 모듈과 외부 라이브러리를 사용하여 개발 프로세스를 단순화하고 효율적으로 작업할 수 있게 도와줍니다.
## 모듈 활용하기
파이썬에서 **모듈**은 필요한 함수, 클래스 및 변수가 포함된 코드 집합입니다. 모듈은 코드의 재사용을 촉진하며, 관련된 코드를 하나의 공간에 유지하고 쉽게 찾을 수 있게 합니다. 다양한 파이썬 내장 모듈을 활용하면 시간과 노력을 절약하고 안정성을 높일 수 있습니다.
다음은 파이썬 표준라이브러리에서 제공하는 `random` 모듈의 사용 예시입니다.
```python
import random
# 1부터 10까지 무작위로 선택된 숫자 출력
random_number = random.randint(1, 10)
print(random_number)
```
위의 예시에서는 `random` 모듈을 `import`하여 사용하고 있습니다. `random` 모듈의 `randint()` 함수를 호출하여 1부터 10까지의 무작위 정수를 선택하고 이를 출력합니다. 이러한 모듈들은 파이썬에서 기본적으로 제공되므로 따로 설치하지 않아도 사용할 수 있습니다.
## 외부 라이브러리 활용하기
파이썬의 장점 중 하나는 다양한 외부 라이브러리의 활용이 가능하다는 것입니다. 외부 라이브러리는 파이썬 개발자들이 만든 유용한 도구이며, 코드를 효과적으로 작성하고 작업을 간단하게 만들어 줍니다.
예를 들어, 데이터 시각화 작업을 할 때 `matplotlib` 라이브러리를 사용할 수 있습니다. 다음은 `matplotlib` 라이브러리를 사용하여 간단한 선 그래프를 그리는 예시입니다.
```python
import matplotlib.pyplot as plt
# x축과 y축 데이터
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# 선 그래프 그리기
plt.plot(x, y)
# 그래프 표시
plt.show()
```
위의 코드에서는 `matplotlib.pyplot` 모듈을 `plt`라는 이름으로 `import`하여 사용하고 있습니다. `plot()` 함수를 사용하여 `x`와 `y` 데이터를 선 그래프로 그린 뒤, `show()` 함수를 호출하여 그래프를 표시합니다.
외부 라이브러리는 파이썬에서 기본적으로 제공되지 않기 때문에, 해당 라이브러리를 설치해야 사용할 수 있습니다. 대부분의 외부 라이브러리는 `pip`를 사용하여 쉽게 설치할 수 있습니다.
## 마무리
모듈과 외부 라이브러리는 파이썬 개발에 있어서 매우 유용한 도구입니다. 파이썬 내장 모듈을 통해 코드의 재사용성을 높일 수 있고, 외부 라이브러리를 활용하여 다양한 작업을 간편하게 처리할 수 있습니다.
따라서, 개발 프로세스에서 모듈과 외부 라이브러리의 활용을 고려해야 합니다. 코드의 재사용성을 높이고 효율적으로 작업할 수 있는 모듈과 외부 라이브러리의 활용은 개발자에게 큰 도움이 될 것입니다.
|
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Start by Capgemini</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Start by Capgemini</h1>
<nav>
<button><a href="index.html">Página Inicial</a></button>
<button><a href="kanban.html">Kanban</a></button>
<button><a href="diario.html">Diário de Estudos</a></button>
</nav>
</header>
<main>
<h2>Preparatório para o Programa</h2>
<details>
<summary>Trilha Java - Capgemini</summary>
<ol>
<li>Introdução à Lógica de Programação</li>
<li>Lógica de Programação e Algoritmos I</li>
<li>Lógica de Programação e Algoritmos II</li>
<li>Lógica de Programação e Algoritmos III</li>
<li>Versionamento de Código - Git e GitHub</li>
<li>Fundamentos de HTML5 Módulo 1</li>
<li>Fundamentos de HTML5 Módulo 2</li>
<li>Fundamentos de HTML5 Módulo 3</li>
<li>Fundamentos de CSS3</li>
<li>JavaScript, JQuery e Ajax</li>
<li>TypeScript</li>
<li>CSS Avançado</li>
<li>HTML Avançado</li>
<li>React</li>
<li>Angular</li>
<li>Criando APIs com Angular</li>
<li>Java Fundamentos</li>
<li>Linguagem de Programação em Java</li>
<li>Programação Orientada a Objetos em Java</li>
<li>Java Web</li>
<li>Spring Boot Framework</li>
<li>Metodologias Ágeis e Engenharia de Software</li>
</ol>
</details>
<details>
<summary>Cursos e Certificados - Concluídos</summary>
<ol>
<li>
<a href="Introducao-a-Logica.html">Lógica de Programação e Pensamento Computacional -
67h (2021-2023)</a>
</li>
<li>
<a href="HTML5-e-CSS3.html">HTML5 e CSS3 - 77h (2022-2023)</a>
</li>
</ol>
</details>
<h2>Metodologia de Estudos</h2>
<p>
A preparação para o Programa Start by Capgemini com foco no FullStack em Java com Angular no
Front-end será desenvolvida através de cursos de diversas escolas de tecnologia. Nomes como Udemy, Alura, Ada (antiga LetsCode), FIAP, TIM Tech, entre outros, figurarão como principais provedoras dos conhecimentos necessários à formação desejada pela empresa Multinacional Capgemini para o cargo de Analista de Desenvolvimento em Java.
</p>
<p>
O Programa Start by Capgemini oferece uma trilha preparatória para formar seus futuros
desenvolvedores, porém, sob meu ponto de vista pessoal, achei a didática dos cursos que compõem a trilha um tanto difícil para iniciantes. Por esse motivo, decidi estudar através de outras fontes para alcançar o êxito nessa
importante missão.
</p>
<p>
Os cursos, bem como a sua ordem será organizada de acordo com o que é oferecido pelo
próprio Programa Start by Capgemini. A cada curso que o Programa oferece como base de conhecimento buscarei, em outras plataformas, cursos equivalente para a completa aquisição das habilidades pedidas pela Capgemini. A preferência na escolha dos cursos será por aqueles que oferecem certificados verificáveis para acrescentar ao escopo deste projeto. Pode ser que se faça necessário mais de um curso para cobrir um determinado tópico. Em outras situações, pode ser que um único curso abranja mais de um tópico
</p>
</main>
</body>
</html>
|
package com.firstapp.foodorderapp.ui;
import static com.firstapp.foodorderapp.utils.Constants.CONFLICT_CODE;
import static com.firstapp.foodorderapp.utils.Constants.MAIN_SHARED_PREFERENCE;
import static com.firstapp.foodorderapp.utils.Constants.OK_CODE;
import static com.firstapp.foodorderapp.utils.Constants.UNAUTHORIZED_CODE;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.firstapp.foodorderapp.R;
import com.firstapp.foodorderapp.api.UserApi;
import com.firstapp.foodorderapp.model.User;
import com.firstapp.foodorderapp.utils.Functions;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.io.IOException;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import retrofit2.Call;
import retrofit2.Response;
@AndroidEntryPoint
public class SignInActivity extends AppCompatActivity {
MaterialButton submitButton;
TextInputEditText emailInput;
TextInputEditText passwordInput;
TextView warning;
InputMethodManager inputMethodManager;
SharedPreferences sharedPreferences;
View loading;
ActivityResultLauncher<Intent> googleSignInLauncher;
@Inject
FirebaseAuth firebaseAuth;
@Inject
UserApi userApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
getWindow().setStatusBarColor(getColor(R.color.white_bg));
Functions.setStatusBarTextToDark(this);
inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
sharedPreferences = getSharedPreferences(MAIN_SHARED_PREFERENCE, MODE_PRIVATE);
// get views
loading = findViewById(R.id.viewLoading);
emailInput = findViewById(R.id.ipEmail);
passwordInput = findViewById(R.id.ipPassword);
submitButton = findViewById(R.id.btnSubmit);
warning = findViewById(R.id.tvWarning);
// add event listeners
submitButton.setOnClickListener((v) -> {
if (Functions.isInternetConnected(this)) {
warning.setVisibility(View.GONE);
String email = String.valueOf(emailInput.getText());
String password = String.valueOf(passwordInput.getText());
if (isCredentialsValid(email, password))
signInWithEmailAndPassword(email, password);
} else Functions.notifyNoInternetConnection(SignInActivity.this);
});
googleSignInLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
this::handleSignInWithGoogle
);
}
public void googleSignInEventHandler(View v) {
if (Functions.isInternetConnected(this))
requestGoogleSignIn();
else Functions.notifyNoInternetConnection(SignInActivity.this);
}
private void requestGoogleSignIn() {
GoogleSignInOptions options = new GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.google_auth_id_token))
.requestEmail()
.build();
GoogleSignInClient client = GoogleSignIn.getClient(this, options);
client.revokeAccess();
googleSignInLauncher.launch(client.getSignInIntent());
}
private boolean isCredentialsValid(String email, String password) {
boolean valid = true;
String promptText = null;
String emailPattern = "^[0-9A-Za-z.+-_%]+@[a-z0-9A-Z-.]+\\.[a-zA-Z0-9]{2,}$";
String passwordPattern = "^[a-zA-Z0-9]{6,}$";
// validate email
if (!email.matches(emailPattern)) {
valid = false;
promptText = "The email is invalid!";
}
// validate password
if (password.length() < 6) {
valid = false;
promptText = "The length of password must be at least 8";
} else if (!password.matches(passwordPattern)) {
valid = false;
promptText = "The password must only contains letters, numbers";
}
if (!valid) {
createVibration();
warning.setVisibility(View.VISIBLE);
warning.setText(promptText);
} else {
warning.setVisibility(View.INVISIBLE);
}
return valid;
}
void createVibration() {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(
VibrationEffect.createOneShot(75, VibrationEffect.DEFAULT_AMPLITUDE)
);
}
void signInWithEmailAndPassword(String email, String password) {
showLoading();
new Thread(() -> {
Call<User> task = userApi.signUserInWithEmailAndPassword(email, password);
try {
Response<User> res = task.execute();
if (res.code() == OK_CODE) {
// login success
startSignUserIn(email, password);
} else if (res.code() == CONFLICT_CODE) {
// invalid password
hideLoading();
promptInvalidPassword();
} else if (res.code() == UNAUTHORIZED_CODE) {
// email is not existing
createUserWithEmailAndPassword(email, password);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}).start();
}
private void createUserWithEmailAndPassword(String email, String password) {
firebaseAuth
.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = task.getResult().getUser();
assert firebaseUser != null : "Firebase user is null";
Call<User> req = userApi.createUser(
new User(firebaseUser.getUid(), email, password)
);
new Thread(() -> {
try {
req.execute();
} catch (IOException e) {
throw new RuntimeException(e);
}
}).start();
startSignUserIn(email, password);
}
hideLoading();
});
}
@SuppressLint("SetTextI18n")
private void promptInvalidPassword() {
runOnUiThread(() -> {
createVibration();
warning.setVisibility(View.VISIBLE);
warning.setText("Invalid password");
});
}
private void startSignUserIn(String email, String password) {
firebaseAuth
.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful())
handleAuthenticationOK(task.getResult());
hideLoading();
}
});
}
private void showLoading() {
runOnUiThread(() -> loading.setVisibility(View.VISIBLE));
}
private void hideLoading() {
runOnUiThread(() -> loading.setVisibility(View.GONE));
}
private void handleSignInWithGoogle(ActivityResult activityResult) {
showLoading();
GoogleSignInAccount account = GoogleSignIn.getSignedInAccountFromIntent(
activityResult.getData()
).getResult();
AuthCredential credential =
GoogleAuthProvider.getCredential(account.getIdToken(), null);
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
new Thread(() -> {
FirebaseUser firebaseUser = task.getResult().getUser();
assert firebaseUser != null : "Firebase user is null";
Call<User> req = userApi.signUserInWithProvider(firebaseUser.getUid());
try {
Response<User> res = req.execute();
if (res.code() != OK_CODE)
userApi.createUser(
new User(firebaseUser.getUid(), firebaseUser.getEmail(), null)
).execute();
handleAuthenticationOK(task.getResult());
hideLoading();
} catch (IOException e) {
throw new RuntimeException(e);
}
}).start();
} else {
hideLoading();
Toast.makeText(
SignInActivity.this,
"Sign in failed",
Toast.LENGTH_SHORT).show();
}
});
}
private void handleAuthenticationOK(AuthResult authResult) {
FirebaseUser firebaseUser = authResult.getUser();
assert firebaseUser != null : "Firebase user is null!";
Functions.cacheUID(this, firebaseUser.getUid());
startActivity(new Intent(this, MainActivity.class));
finish();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Functions.clearInputFocusWhenClickOutside(ev, this);
return super.dispatchTouchEvent(ev);
}
}
|
import {Component, EventEmitter, Input, OnInit, Output, SimpleChanges} from "@angular/core";
import {TreeNode} from "angular-tree-component";
import {isNullOrUndefined} from "util";
import {RzhtoolsService} from "../../../core/services/rzhtools.service";
import {GoodsService} from "../goods.service";
import {SettingsService} from "../../../core/settings/settings.service";
declare var $: any;
@Component({
selector: 'app-goodscat',
templateUrl: './goodscat.component.html',
styleUrls: ['./goodscat.component.scss']
})
export class GoodscatComponent implements OnInit {
@Input() isOpen: boolean; //是否开启
addIsShow: boolean; //遮罩层是否开启
@Output() close = new EventEmitter(); //关闭
@Output() parentNodes: EventEmitter<Array<any>> = new EventEmitter(); //父级信息
nodes: Array<any> = new Array(); //数据源
selName: string; //选中的信息名
selCode: string; //选中的信息的code
inputCategoryName: string; //添加---分类名
inputSummary: string; //添加---分类说明
upInfo: any; //修改数据信息
customTemplateStringOptions = { //树结构参数
isExpandedField: 'expanded',
idField: 'uuid',
allowDrag: true
};
constructor(private tools: RzhtoolsService, private goods: GoodsService) {
}
ngOnInit() {
let me = this; //查询分类列表信息
me.nodes = me.tools.arrayToTree(me.goods.queryGoodsCats(), 'goodsCategoryCode'); //查询并格式化分类列表信息
me.parentNodes.emit(me.nodes); //给父组件传递数据
}
/**
* 监听组件变化
* @param changes
*/
ngOnChanges(changes: SimpleChanges) {
let me = this;
me.parentNodes.emit(me.nodes); //给父组件传递数据
}
/**
* 关闭类型页面
*/
closeGoodscat() {
this.close.emit();
}
/**
* 子节点数量
* @param node
* @returns {string}
*/
childrenCount(node: TreeNode): string {
return node && node.children ? `(${node.children.length} ` + SettingsService.I18NINFO.swat.e133 + `)` : '';
}
/**
* 设置分类上级编码
*/
addGoodsType(goodsCategoryCode?: string, categoryName?: string) {
let me = this;
me.selName = categoryName, me.selCode = goodsCategoryCode;
}
/**
* 设置要修改的分类的信息
*/
getUpdateGoodsTypeInfo(data) {
let me = this;
me.upInfo = data;
}
/**
* 添加分类信息
*/
submitGoodsType() {
let me = this, isTrue: Boolean = false;
if (isNullOrUndefined(me.inputCategoryName)) { //类型名未填写
me.tools.rzhAlt("error", SettingsService.I18NINFO.swat.e102, SettingsService.I18NINFO.goods.typeName);
return;
}
isTrue = me.goods.addGoodsType(me.inputCategoryName, me.inputSummary, me.selCode);
if (isTrue) {
me.inputCategoryName = null, me.inputSummary = null;//重置信息
me.nodes = me.tools.arrayToTree(me.goods.queryGoodsCats(), 'goodsCategoryCode'); //查询并格式化分类列表信息
}
}
/**
* 修改分类信息
*/
updateGoodsType() {
let me = this, isTrue: Boolean = false;
isTrue = me.goods.updateGoodsType(me.upInfo);
if (isTrue) {
me.upInfo = null;//重置信息
me.nodes = me.tools.arrayToTree(me.goods.queryGoodsCats(), 'goodsCategoryCode'); //查询并格式化分类列表信息
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.