text
stringlengths 184
4.48M
|
---|
import type { StoryObj, Meta } from "@storybook/react";
import * as DocBlock from "@storybook/blocks";
import { createRemixStub } from "@remix-run/testing";
import { http, delay, HttpResponse } from "msw";
import Step3 from "./route";
import { getRegStep2 } from "~/requests/getRegStep2/getRegStep2";
import { postRegStep2 } from "~/requests/postRegStep2/postRegStep2";
const meta = {
title: "Страницы/Регистрация/Шаг3",
component: Step3,
tags: ["autodocs"],
parameters: {
layout: {
padded: false,
},
docs: {
page: () => (
<>
<DocBlock.Title />
<h2>Адрес страницы: /registration/step3</h2>
<h3>Используемые запросы:</h3>
<p>
getRegStep3() - VITE_REG_STEP_3 - {import.meta.env.VITE_REG_STEP_3}
</p>
<p>
postRegStep3() - VITE_REG_STEP_3 - {import.meta.env.VITE_REG_STEP_3}
</p>
</>
),
},
},
} satisfies Meta<typeof Step3>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Primary: Story = {
name: "Страница",
decorators: [
(Story) => {
const RemixStub = createRemixStub([
{
path: "/",
Component: Story,
loader: async () => {
const data = await getRegStep2();
return data;
},
action: async () => {
const data = await postRegStep2({ test: "test" });
return data;
},
},
]);
return <RemixStub />;
},
],
parameters: {
msw: {
handlers: [
http.get(import.meta.env.VITE_REG_STEP_2, async () => {
await delay(2000);
return HttpResponse.json({
inputs: [
{
inputtype: "text",
name: "weight",
value: "",
placeholder: "Вес",
validation: "default",
},
{
inputtype: "select",
name: "height",
value: "",
placeholder: "Рост",
validation: "default",
options: [
{
value: "35.5",
label: "35.5",
disabled: false,
},
{
value: "41",
label: "41",
disabled: false,
},
{
value: "45",
label: "45",
disabled: false,
},
],
},
{
inputtype: "select",
name: "clothes",
value: "",
placeholder: "Размер одежды",
validation: "default",
options: [
{
value: "44-46",
label: "44-46",
disabled: false,
},
{
value: "46-48",
label: "46-48",
disabled: false,
},
{
value: "48-50",
label: "48-50",
disabled: false,
},
],
},
{
inputtype: "select",
name: "hairColor",
value: "",
placeholder: "Цвет волос",
validation: "default",
options: [
{
value: "light",
label: "светлые",
disabled: false,
},
{
value: "dark",
label: "тёмные",
disabled: false,
},
],
},
{
inputtype: "select",
name: "hairLenght",
value: "",
placeholder: "Длина волос",
validation: "default",
options: [
{
value: "short",
label: "Короткие",
disabled: false,
},
{
value: "normal",
label: "Средние",
disabled: false,
},
{
value: "long",
label: "Длинные",
disabled: false,
},
],
},
{
inputtype: "file",
name: "driverLicence",
value: "",
url: "http://preprod.marriator-api.fivecorners.ru/api/saveFile",
placeholder: "Приложи документ",
validation: "default",
heading: "Водительское удостоверение",
dividerTop: true,
helperInfo: {
text: "Для подтверждения приложи фотографию документа",
},
},
{
inputtype: "file",
name: "medicalDriverLicence",
value: "",
url: "http://preprod.marriator-api.fivecorners.ru/api/saveFile",
placeholder: "Приложи документ",
validation: "default",
heading: "Медицинский допуск к управлению ТС",
helperInfo: {
text: "Для подтверждения приложи фотографию документа",
},
},
{
inputtype: "file",
name: "anyLicence",
value: "",
url: "http://preprod.marriator-api.fivecorners.ru/api/saveFile",
placeholder: "Приложи документ",
validation: "default",
heading: "Пример любого допуска к работе",
helperInfo: {
text: "Для подтверждения приложи фотографию документа",
},
},
{
inputtype: "radio",
value: "",
name: "medBook",
validation: "default",
dividerTop: true,
heading: "Медкнижка",
options: [
{
value: "have",
label: "В наличии",
disabled: false,
},
{
value: "dontHave",
label: "На оформлении",
disabled: false,
},
],
},
{
inputtype: "file",
name: "medBookFile",
value: "",
url: "http://preprod.marriator-api.fivecorners.ru/api/saveFile",
placeholder: "Приложи документ",
validation: "default",
helperInfo: {
text: "Для подтверждения приложи фотографию документа",
},
},
],
});
}),
http.post(import.meta.env.VITE_REG_STEP_2, async () => {
await delay(2000);
return HttpResponse.json({
status: "Success",
});
}),
],
},
},
};
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text.Json.Serialization;
#nullable enable
namespace DirectDesk.Models
{
public class Employee
{
public int id { get; set; }
public string names { get; set; }
public string lastName { get; set; }
public string cardId { get; set; }
public string telephone { get; set; }
public DateTime birthdate { get; set; }
public string status { get; set; }
public DateTime hireDate { get; set; }
public int? managerId { get; set; }
public string? managerName { get; set; }
public int? departmentID { get; set; }
public string? departmentName { get; set; }
public DateTime modifiedDate { get; set; }
public int? addressId { get; set; }
public string cityName { get; set; }
public string direction { get; set; }
public Employee
(
int id,
string names,
string lastName,
string cardId,
string telephone,
DateTime birthdate,
string status,
DateTime hireDate,
int? managerId,
string? managerName,
int? departmentID,
string? departmentName,
DateTime modifiedDate,
int? addressId,
string cityName,
string direction
)
{
this.id = id;
this.names = names;
this.lastName = lastName;
this.cardId = cardId;
this.telephone = telephone;
this.birthdate = birthdate;
this.status = status;
this.hireDate = hireDate;
this.managerId = managerId;
this.departmentID = departmentID;
this.departmentName = departmentName;
this.managerName = managerName;
this.modifiedDate = modifiedDate;
this.addressId = addressId;
this.cityName = cityName;
this.direction = direction;
}
public List<SqlParameter> GetParameters()
{
SqlParameter names = new SqlParameter("@NAMES", this.names);
SqlParameter lastName = new SqlParameter("@LAST_NAME", this.lastName);
SqlParameter cardId = new SqlParameter("@CARD_ID", this.cardId);
SqlParameter telephone = new SqlParameter("@TELEPHONE", this.telephone);
SqlParameter birthdate = new SqlParameter("@BIRTHDATE", this.birthdate);
birthdate.SqlDbType = System.Data.SqlDbType.Date;
SqlParameter status = new SqlParameter("@STATUS", this.status);
status.SqlDbType = System.Data.SqlDbType.Bit;
SqlParameter hireDate = new SqlParameter("@HIRE_DATE", this.hireDate);
hireDate.SqlDbType = System.Data.SqlDbType.Date;
//EMPLOYEE_MANAGER puede ser nulo por lo que en caso de que departmentID
//no tenga valor el valor del sqlparameter debe ser tipo SQLInt32.Null para evitar errores
SqlParameter managerId = new SqlParameter("@MANAGER_ID", (this.managerId.HasValue) ? this.managerId : SqlInt32.Null);
managerId.SqlDbType = System.Data.SqlDbType.Int;
//EMPLOYEE_DEPARTMENT puede ser nulo por lo que en caso de que departmentID
//no tenga valor el valor del sqlparameter debe ser tipo SQLInt32.Null para evitar errores
SqlParameter departmentID = new SqlParameter("@DEPARTMENT_ID", (this.departmentID.HasValue) ? this.departmentID : SqlInt32.Null);
departmentID.SqlDbType = System.Data.SqlDbType.Int;
SqlParameter modifiedDate = new SqlParameter("@MODIFIED_DATE", this.modifiedDate);
modifiedDate.SqlDbType = System.Data.SqlDbType.DateTime;
SqlParameter addressId = new SqlParameter("@ADDRESS_ID", this.addressId);
return new List<SqlParameter>() { names, lastName, cardId, telephone, birthdate, status, hireDate, managerId, departmentID, modifiedDate, addressId };
}
public string GetInsertInsertString()=>
@"INSERT INTO EMPLOYEE
(
EMPLOYEE_NAME,
EMPLOYEE_LAST_NAME,
EMPLOYEE_CARD_ID,
EMPLOYEE_TELEPHONE,
EMPLOYEE_BIRTHDATE,
EMPLOYEE_HIRE_DATE,
EMPLOYEE_STATUS,
EMPLOYEE_MANAGER,
EMPLOYEE_DEPARTMENT,
MODIFIED_DATE,
ADDRESS_ID
)
VALUES
(
@NAMES,
@LAST_NAME,
@CARD_ID,
@TELEPHONE,
@BIRTHDATE,
@HIRE_DATE,
@STATUS,
@MANAGER_ID,
@DEPARTMENT_ID,
@MODIFIED_DATE,
@ADDRESS_ID
); ";
}
}
|
#include <windows.h>
#include <iostream>
#include <math.h>
#include <conio.h>
#define PI 3.14159265359
HANDLE hOut;
int BUFFER_WIDTH;
int BUFFER_HEIGHT;
char* TXTBUFFER;
bool setConsoleFontSize(int width, int height) {
CONSOLE_FONT_INFOEX fontInfo;
fontInfo.cbSize = sizeof(fontInfo);
if (!GetCurrentConsoleFontEx(hOut, FALSE, &fontInfo)) {
return false;
}
fontInfo.dwFontSize.X = width;
fontInfo.dwFontSize.Y = height;
if (!SetCurrentConsoleFontEx(hOut, FALSE, &fontInfo)) {
return false;
}
return true;
}
BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) {
switch (dwCtrlType) {
case CTRL_CLOSE_EVENT:
delete[] TXTBUFFER;
return TRUE;
default:
return FALSE;
}
}
void initializeWindow(const char* p, int width, int height, int fontwidth, int fontheight) {
SetConsoleTitle(TEXT(p));
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
setConsoleFontSize(fontwidth,fontheight);
if (hOut == INVALID_HANDLE_VALUE) { return; }
DWORD dwMode = 0;
if (!GetConsoleMode(hOut, &dwMode)) { return; }
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(hOut, dwMode)) { return; }
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, width, height, TRUE);
CONSOLE_SCREEN_BUFFER_INFO scrBufferInfo;
GetConsoleScreenBufferInfo(hOut, &scrBufferInfo);
short winWidth = scrBufferInfo.srWindow.Right - scrBufferInfo.srWindow.Left + 1;
short winHeight = scrBufferInfo.srWindow.Bottom - scrBufferInfo.srWindow.Top + 1;
short scrBufferWidth = scrBufferInfo.dwSize.X;
short scrBufferHeight = scrBufferInfo.dwSize.Y;
COORD newSize;
newSize.X = scrBufferWidth;
newSize.Y = winHeight;
int Status = SetConsoleScreenBufferSize(hOut, newSize);
GetConsoleScreenBufferInfo(hOut, &scrBufferInfo);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(hOut, &cursorInfo);
cursorInfo.bVisible = false;
SetConsoleCursorInfo(hOut, &cursorInfo);
BUFFER_WIDTH = scrBufferInfo.srWindow.Right - scrBufferInfo.srWindow.Left + 1;
BUFFER_HEIGHT = scrBufferInfo.srWindow.Bottom - scrBufferInfo.srWindow.Top + 1;
TXTBUFFER = new char[BUFFER_WIDTH * BUFFER_HEIGHT];
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
}
void plot(int x, int y, char p){
int index = y*BUFFER_WIDTH+x;
if(index>0 && index<BUFFER_WIDTH*BUFFER_HEIGHT){TXTBUFFER[index]=p;}
}
void vline(int x, int y, char p, int height){
for(int h=0;h<height;h++){
plot(x,y+h,p);
}
}
void line(int x1, int y1, int x2, int y2, char p) {
int dx = abs(x2 - x1);
int dy = abs(y2 - y1);
int sx = x1 < x2 ? 1 : -1;
int sy = y1 < y2 ? 1 : -1;
int err = dx - dy;
while (x1 != x2 || y1 != y2) {
plot(x1, y1, p);
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x1 += sx;
}
if (e2 < dx) {
err += dx;
y1 += sy;
}
}
plot(x2, y2, p); // plot the end point
}
void rect(int x, int y, int width, int height, char p){
for(int w=0;w<width;w++){
for(int h=0;h<height;h++){
plot(x+w,y+h,p);
}
}
}
void clear() {
std::fill(TXTBUFFER, TXTBUFFER + BUFFER_WIDTH * BUFFER_HEIGHT, ' ');
}
void render() {
COORD C;C.X=0;C.Y=0;
SetConsoleCursorPosition(hOut, C);
DWORD written;
WriteConsole(hOut, TXTBUFFER, BUFFER_WIDTH * BUFFER_HEIGHT, &written, NULL);
}
int xdim = 12;
int ydim = 15;
int map[15][12] = {
{3,2,1,1,1,1,1,1,1,1,2,3},
{2,0,0,0,0,0,0,0,0,0,0,2},
{1,0,0,0,0,1,2,0,0,0,0,1},
{1,0,0,3,0,0,0,0,3,0,0,1},
{1,0,0,2,0,0,0,0,2,0,0,1},
{1,0,0,1,0,0,0,0,1,0,0,1},
{1,0,0,1,0,0,0,0,1,0,0,1},
{1,0,0,1,0,0,0,0,1,0,0,1},
{1,0,0,1,0,0,0,0,1,0,0,1},
{1,0,0,1,0,0,0,0,1,0,0,1},
{1,0,0,2,0,0,0,0,2,0,0,1},
{1,0,0,3,0,0,0,0,3,0,0,1},
{1,0,0,0,0,1,2,0,0,0,0,1},
{2,0,0,0,0,0,0,0,0,0,0,2},
{3,2,1,1,1,1,1,1,1,1,2,3}
};
float playerx;
float playery;
float fov;
float angInc;
float angSpeed;
float playerangle;
float playerspeed;
int cw;
int ch;
float distanceToProj;
void movePlayer(int key) {
float dist = 1;
switch (key) {
case 72:
playerx += cos(playerangle) * dist;
playery += sin(playerangle) * dist;
break;
case 80:
playerx -= cos(playerangle) * dist;
playery -= sin(playerangle) * dist;
break;
case 75:
playerangle -= angSpeed;
if (playerangle < 0)
playerangle += 2 * PI;
break;
case 77:
playerangle += angSpeed;
if (playerangle >= 2 * PI)
playerangle -= 2 * PI;
break;
}
}
void checkInput() {
if (_kbhit()) {
int key = _getch();
movePlayer(key);
}
}
struct Raycast{
float x;
float y;
char p;
};
char texture(int n){
switch (n) {
case 1:
return '#';
break;
case 2:
return '*';
break;
case 3:
return '-';
break;
default:
return ' ';
break;
}
}
Raycast raycast(float angle) {
float px = playerx;
float py = playery;
float dx = 0.5*cos(angle);
float dy = 0.5*sin(angle);
while(true){
if(map[(int)(py/ch)][(int)(px/cw)] != 0){
break;
}
px+=dx;
py+=dy;
}
return Raycast{px,py,texture(map[(int)(py/ch)][(int)(px/cw)])};
}
void drawmap(float scale = 0.3) {
int cw = BUFFER_WIDTH / xdim;
int ch = BUFFER_HEIGHT / ydim;
float anglestart = playerangle - fov / 2;
for (int i = 0; i < BUFFER_WIDTH; i++) {
float ang = anglestart + angInc * i;
auto [x2, y2, p] = raycast(ang);
line(playerx * scale, playery * scale, x2 * scale, y2 * scale, '@');
float distance = sqrt(pow(x2 - playerx, 2) + pow(y2 - playery, 2)) * cos(ang - playerangle) ;
float projectedheight = (ch / distance) * distanceToProj;
vline(i, BUFFER_HEIGHT / 2 - projectedheight / 2, p, projectedheight);
}
for (int x = 0; x < xdim; x++) {
for (int y = 0; y < ydim; y++) {
if (map[y][x] !=0 ) {
rect(x * cw * scale, y * ch * scale, cw * scale, ch * scale, texture(map[y][x]));
}
}
}
}
int main() {
initializeWindow("RAYCASTER", 800, 600,3,3);
playerx = BUFFER_WIDTH/2;
playery = BUFFER_HEIGHT/2;
fov = PI/3;
angInc = fov/BUFFER_WIDTH;
playerangle = PI;
playerspeed = 2;
angSpeed = 0.2;
cw = BUFFER_WIDTH/xdim;
ch = BUFFER_HEIGHT/ydim;
distanceToProj = (BUFFER_WIDTH/2)/tan(fov/2);
while(true) {
checkInput();
clear();
drawmap();
render();
}
}
|
import React, { FC, useEffect, useState } from 'react';
import styled from 'styled-components';
import { ethereumImage } from 'assets';
import { parseEtherUSD } from 'helpers/utilities';
interface IProps {
price?: number;
showDollars?: boolean;
}
const Value: FC<IProps> = ({ price = 0, showDollars = true }) => {
const [USDPrice, setUSDPrice] = useState<string>('0');
useEffect(() => {
const getEtherUSD = async () => {
const parsedEther = await parseEtherUSD(price);
setUSDPrice(parsedEther);
}
if (price > 0) {
getEtherUSD();
}
}, [price]);
return (
<ValueWrapper>
<ValueIcon />
<Amount>{price}</Amount>
{showDollars && <DollarsAmount>{`($${USDPrice})`}</DollarsAmount>}
</ValueWrapper>
);
}
export default Value;
const ValueWrapper = styled.div`
display: flex;
align-items: center;
margin-bottom: 10px;
background: white;
`;
const ValueIcon = styled.div`
width: 20px;
height: 20px;
flex-shrink: 0;
background: transparent url(${ethereumImage}) center center no-repeat;
background-size: contain;
`;
const Amount = styled.div`
font-size: 24px;
@media (max-width: 450px) {
font-size: 18px;
}
`;
const DollarsAmount = styled.div`
font-size: 15px;
margin: 8px 0 0 4px;
color: rgb(112, 122, 131);
@media (max-width: 450px) {
font-size: 12px;
}
`;
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2015 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::mojRhoThermo
Description
Basic thermodynamic properties based on density
SourceFiles
mojRhoThermo.C
\*---------------------------------------------------------------------------*/
#ifndef mojRhoThermo_H
#define mojRhoThermo_H
#include "mojFluidThermo.H"
#include "runTimeSelectionTables.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class mojRhoThermo Declaration
\*---------------------------------------------------------------------------*/
class mojRhoThermo
:
public mojFluidThermo
{
protected:
// Protected data
//- Density field [kg/m^3]
// Named 'mojRhoThermo' to avoid (potential) conflict with solver density
volScalarField rho_;
//- Compressibility [s^2/m^2]
volScalarField psi_;
//- Dynamic viscosity [kg/m/s]
volScalarField mu_;
// Protected Member Functions
//- Construct as copy (not implemented)
mojRhoThermo(const mojRhoThermo&);
public:
//- Runtime type information
TypeName("mojRhoThermo");
//- Declare run-time constructor selection table
declareRunTimeSelectionTable
(
autoPtr,
mojRhoThermo,
fvMesh,
(const fvMesh& mesh, const word& phaseName),
(mesh, phaseName)
);
// Constructors
//- Construct from mesh and phase name
mojRhoThermo
(
const fvMesh&,
const word& phaseName
);
//- Construct from mesh, dictionary and phase name
mojRhoThermo
(
const fvMesh&,
const dictionary&,
const word& phaseName
);
//- Selector
static autoPtr<mojRhoThermo> New
(
const fvMesh&,
const word& phaseName=word::null
);
//- Destructor
virtual ~mojRhoThermo();
// Member functions
// Fields derived from thermodynamic state variables
//- Density [kg/m^3]
virtual tmp<volScalarField> rho() const;
//- Density for patch [kg/m^3]
virtual tmp<scalarField> rho(const label patchi) const;
//- Return non-const access to the local density field [kg/m^3]
virtual volScalarField& rho();
//- Compressibility [s^2/m^2]
virtual const volScalarField& psi() const;
// Access to transport state variables
//- Dynamic viscosity of mixture [kg/m/s]
virtual tmp<volScalarField> mu() const;
//- Dynamic viscosity of mixture for patch [kg/m/s]
virtual tmp<scalarField> mu(const label patchi) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
|
package com.kwm0304.cli.template.security;
import com.kwm0304.cli.StringUtils;
import org.springframework.stereotype.Service;
@Service
public class UserDetailsServiceImplTemplate {
public String genUserDetailsService(String parentDir, String userClass, boolean useLombok) {
String convertedParent = StringUtils.convertPath(parentDir);
String tab = " ";
StringBuilder builder = new StringBuilder();
builder.append("package ").append(convertedParent).append(".service;\n\n")
.append("import ").append(convertedParent).append(".repository.").append(userClass).append("Repository;\n")
.append("import org.springframework.security.core.userdetails.UserDetails;\n")
.append("import org.springframework.security.core.userdetails.UserDetailsService;\n")
.append("import org.springframework.security.core.userdetails.UsernameNotFoundException;\n")
.append("import org.springframework.stereotype.Service;\n\n");
if (useLombok) {
builder.append("@AllArgsConstructor\n");
}
builder.append("@Service\n")
.append("public class UserDetailsServiceImpl implements UserDetailsService {\n")
.append("private final ").append(userClass).append("Repository userRepository;\n");
if (!useLombok) {
builder.append("public UserDetailsServiceImpl(").append(userClass).append("Repository userRepository) { this.userRepository = userRepository; }\n");
}
builder.append(tab).append("@Override\n")
.append(tab).append("public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {\n")
.append(tab).append(tab).append("return userRepository.findByUsername(username)\n")
.append(tab).append(tab).append(tab).append(".orElseThrow(() -> new UsernameNotFoundException(\"User not found\"));\n")
.append(tab).append("}\n")
.append("}");
return builder.toString();
}
}
|
import supertest, { SuperTest } from 'supertest'
import { createModule } from './utils/create-module.util'
import { HttpStatus, INestApplication } from '@nestjs/common';
import { AbstractCarRepository } from '../domain/repositories/car.repository';
import { CarDocument } from '../domain/models/car.model';
describe('Car Controller - [DELETE] /car/:carId', () => {
let nestApp: INestApplication
let carRepository: AbstractCarRepository<CarDocument>
let request: SuperTest<any>
beforeAll(async () => {
const { app, module } = await createModule()
nestApp = app
carRepository = module.get<AbstractCarRepository<CarDocument>>(
AbstractCarRepository
)
request = supertest(app.getHttpServer())
})
it('should delete the car by id', async () => {
const car = {
carname: 'BMW',
colorId: '63b35ace98c8ed2a26b10281',
modelId: '63b35ace98c8ed2a26b10282',
kmId: '63b35ace98c8ed2a26b10283',
yearId: '63b35ace98c8ed2a26b10284',
price: 350,
lt: 45.76,
lg: 34.56,
userId: '63b35ace98c8ed2a26b1028b',
}
const createdCarResponse = await request
.post('/car')
.send(car)
.expect(HttpStatus.CREATED)
const createdCar = createdCarResponse.body.payload.car
await request.delete(`/car/${createdCar._id}`).expect(HttpStatus.OK)
})
afterEach(async () => {
await carRepository.deleteMany({})
})
afterAll(async () => {
await nestApp.close()
})
})
|
<template>
<div class="dropdown">
<div class="selected" :class="{ open: open }" @click="open = !open">
{{ selected }}
</div>
<div class="items" v-show="open">
<div
v-for="(option, index) in options"
:key="index"
@click="select(option)"
>
{{ option }}
<span v-if="option === selected">
<fa-icon :icon="['fas', 'check']"></fa-icon>
</span>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Dropdown',
props: {
value: {
type: String,
required: true
},
options: {
type: Array,
required: true
},
callback: {
type: Function,
required: true
}
},
data() {
return {
selected: this.value,
open: false
};
},
methods: {
select(option) {
this.selected = option;
this.open = false;
this.callback(this.selected);
}
}
};
</script>
<style scoped>
.dropdown {
position: relative;
width: 60%;
color: var(--clr-text);
background-color: var(--clr-elements);
box-shadow: 0 1px 3px var(--clr-box-shadow);
border-radius: 10px;
}
.selected {
background-color: var(--clr-elements);
color: var(--clr-text);
padding: 1rem 2rem;
cursor: pointer;
font-weight: var(--fw-medium);
font-size: 0.75rem;
border-radius: 10px;
}
.selected::after {
position: absolute;
content: '';
top: 22px;
right: 1em;
width: 0;
height: 0;
border: 5px solid transparent;
border-color: var(--clr-input) transparent transparent transparent;
}
.items {
color: var(--clr-text);
border-radius: 6px;
overflow: hidden;
position: absolute;
background-color: var(--clr-elements);
top: 4rem;
left: 0;
right: 0;
z-index: 10;
}
.items div {
display: flex;
justify-content: space-between;
color: var(--clr-text);
padding: 0.6rem 1rem;
cursor: pointer;
}
.items div:hover {
background-color: var(--clr-input-hover);
}
@media (min-width: 1440px) {
.dropdown {
width: 50%;
margin-left: 1rem;
}
.selected::after {
top: 26px;
}
}
</style>
|
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
name: 'Home',
component: () => import('@/views/HomeView.vue')
},
{
path: '/settings',
name: 'Settings',
component: () => import('@/views/SettingsView.vue')
},
{
path: '/:pathMatch(.*)*',
component: () => import('@/views/PageNotFound.vue')
}
]
})
export default router
|
import datetime
def is_leap_year(year):
# 判断是否为闰年
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False
def get_num_of_days_in_month(year, month):
# 给定年月返回月份的天数
if month in (1, 3, 5, 7, 8, 10, 12):
return 31
elif month in (4, 6, 9, 11):
return 30
elif is_leap_year(year):
return 29
else:
return 28
def get_total_num_of_day(year, month):
# 自1800年1月1日以来过了多少天
days = 0
for y in range(1800, year):
if is_leap_year(y):
days += 366
else:
days += 365
for m in range(1, month):
days += get_num_of_days_in_month(year, m)
return days
def get_start_day(year, month):
# 返回当月1日是星期几
return 3 + get_total_num_of_day(year, month) % 7
# 字典
month_dict = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June',
7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}
def get_month_name(month):
# 返回当月的名称
return month_dict[month]
def print_month_title(year, month):
# 打印日历的首部
print(' ', get_month_name(month), ' ', year, ' ')
print('-------------------------------------')
print(' Sun Mon Tue Wed Thu Fri Sat')
def print_month_body(year, month):
i = get_start_day(year, month)
if i != 7:
print(' ', end='')
print(' ' * i, end='')
for j in range(1, get_num_of_days_in_month(year, month) + 1):
print('%5d' % j, end='')
i += 1
if i % 7 == 0:
print('')
# 主函数部分
month = datetime.datetime.now().month
year = datetime.datetime.now().year
print_month_title(year, month)
print_month_body(year, month)
|
#ifndef PIANO_SERIAL_H
#define PIANO_SERIAL_H
#include <istream>
#include <map>
#include <ostream>
#include <string>
#include <cstdint>
class Serial {
public:
enum Parity {
NONE = 0,
ODD = 1,
EVEN = 2
};
enum StopBits {
ONE = 0,
ONE_AND_A_HALF = 1,
TWO = 2
};
struct Settings {
Parity parity;
StopBits stop_bits;
unsigned int byte_size;
};
constexpr static const Settings ARDUINO_SETTINGS = {
Parity::NONE,
StopBits::ONE,
8};
static const std::map<std::string, Parity> PARITY_MAP;
static const std::map<std::string, StopBits> STOPBIT_MAP;
public:
virtual bool begin(const std::string &port, unsigned int baud, Settings settings) = 0;
virtual void end() = 0;
virtual std::size_t read(std::uint8_t *output, std::size_t count) = 0;
};
std::ostream &operator<<(std::ostream &os, const Serial::Parity &par);
std::ostream &operator<<(std::ostream &os, const Serial::StopBits &sb);
#endif // !defined(PIANO_SERIAL_H)
|
#' Get reference table from package data
#'
#' The first time, the function will read from disk, the second time from the environment. In the case of a necessary update the new data will be saved to the environment for the current session.
#' You can use this table to look at the reference tables and if necessary extract respective classification codes by hand. In general we would recommend the function `ct_commodity_lookup` for this purpose. It uses the present function in the backend.
#' @param dataset_id The dataset ID, which is either partner, reporter or a valid classification scheme.
#' @inheritParams cr_get_data
#' @export
#' @returns a tidy dataset with a reference table
#'
cr_get_ref_table <- function(dataset_id, update = FALSE, verbose = FALSE) {
valid_list <-
c("flow",
"freq",
"indicators",
"partner",
"product",
"reporter",
"stat_procedure",
"time"
)
## check dataset id for valid values
rlang::arg_match(dataset_id, values = valid_list)
## attempt to return the data from the environment first
data <- get(dataset_id, envir = cr_env)
## if the dataset is not yet loaded into the environment
## read it from disk and save to environment
if(is.null(data)){
data <- fs::path_package(paste0('extdata/',dataset_id,'.rds'),
package = 'comRex') |>
readr::read_rds()
assign(dataset_id,data,envir = cr_env)
}
if(update & any(dataset_id %in% cr_env$updated)){
## if update is true, but dataset_id has already been updated once
## only return message
if (verbose) {
cli::cli_inform(c("i" = paste0("Already checked for updates for ",
dataset_id,' in this session.')))
}
return(data)
} else if(update){
## if update is true and not yet updated in this session inform user that update process is starting
if (verbose) {
cli::cli_inform(c("i" = paste0("Attempting to update reference table: ",
dataset_id)))
}
## download new reference table from the UN
data_new <- cr_download_ref_table(dataset_id)
if(unique(data_new$last_modified)>unique(data$last_modified)){
## if the date last modified, returned in the header is newer than the old data
if (verbose) {
cli::cli_inform(c("i" = paste0("Updated reference tables ",
dataset_id,
" with new data, last modified on: ",
unique(data_new$last_modified)))) # nolint
}
## write to environment and overwrite old data
assign(dataset_id,data_new,envir = cr_env)
## let environment variable know that dataset has been updated
cr_env$updated <- c(cr_env$updated,dataset_id)
return(data_new)
} else {
## if last_modified is not newer, let user know that datasets are up to date.
if (verbose) {
cli::cli_inform(c("i" = paste0('No update necessary for table ',
dataset_id,'.')))
}
## save in env variable, that update has been checked in this session
cr_env$updated <- c(cr_env$updated,dataset_id)
return(as.data.frame(data))
}
} else {
## if no update parameter passed on, just return the data read from disk or the env
return(as.data.frame(data))
}
}
#' Downloading the references tables from UN Comtrade
#'
#' @noRd
cr_download_ref_table <- function(dataset_id) {
response <- httr2::request('https://ec.europa.eu/eurostat/search-api/datasets/ds-045409/languages/en') |> # nolint
httr2::req_perform()
last_modified <- response |>
httr2::resp_body_json(simplifyVector = T) |>
purrr::pluck("lastUpdateDate")|>
as.POSIXct( format="%d/%m/%Y %H:%M:%S")
list_of_datasets <- response |>
httr2::resp_body_json(simplifyVector = T) |>
purrr::pluck("dimensions") |>
poorman::group_split(code) |>
purrr::map_dfr(function(.x){
full <- .x$positions[[1]] |>
poorman::rename(code =1, description =2) |>
poorman::mutate(parameter = .x$code,description_parameter = .x$description)
}) |>
poorman::mutate(last_modified = last_modified,
dataset_id = tolower(parameter)) |>
poorman::filter(dataset_id %in% dataset_id)
return(list_of_datasets)
}
|
import React, { useState, useEffect, createContext } from "react";
import { Outlet } from "react-router";
import { transformRestaurantCategories } from "utils/restaurants.js";
const RestaurantsContext = createContext();
const RestaurantsProvider = () => {
const [restaurantsData, setRestaurantsData] = useState([]);
const [categoriesData, setCategoriesData] = useState([]);
const [loadingRestaurants, setLoadingRestaurants] = useState(true);
const [loadingCategories, setLoadingCategories] = useState(true);
const [contextData, setContextData] = useState({
restaurantsData,
setRestaurantsData,
categoriesData,
loadingRestaurants,
loadingCategories,
});
useEffect(() => {
fetch(
"http://frontendsourceryweb.s3-website.eu-central-1.amazonaws.com/restaurants.json"
)
.then((res) => {
if (!res.ok) {
throw Error();
}
return res.json();
})
.then((data) => {
setRestaurantsData(data.restaurants);
})
.finally(() => {
setLoadingRestaurants(false);
});
fetch(
"http://frontendsourceryweb.s3-website.eu-central-1.amazonaws.com/categories.json"
)
.then((res) => {
if (!res.ok) {
throw Error();
}
return res.json();
})
.then((data) => {
setCategoriesData(transformRestaurantCategories(data.categories));
})
.finally(() => {
setLoadingCategories(false);
});
}, []);
useEffect(() => {
setContextData({
restaurantsData,
categoriesData,
setRestaurantsData,
loadingRestaurants,
loadingCategories,
});
}, [restaurantsData, categoriesData, loadingRestaurants, loadingCategories]);
return (
<RestaurantsContext.Provider value={contextData}>
<Outlet />
</RestaurantsContext.Provider>
);
};
export { RestaurantsProvider, RestaurantsContext };
|
<template>
<div>
<div class="container">
<div>
<h1 class="text-primary">SSAFY TUBE</h1>
</div>
<section v-if="isSelecedVideo" class="mt-4">
<div class="ratio ratio-16x9">
<iframe :src="videoSrc" frameborder="0"></iframe>
</div>
<div class="video-title shadow p-3 mb-5 bg-body rounded">
<h4>{{ selectedVideo.snippet.title }}</h4>
</div>
</section>
</div>
</div>
</template>
<script>
import axios from 'axios'
// import _ from 'lodash'
const API_URL = 'https://www.googleapis.com/youtube/v3/search'
const API_KEY = process.env.VUE_APP_YOUTUBE_API_KEY
export default {
name: 'YoutubeView',
created() {
axios.get(API_URL, {
params: {
key: API_KEY,
type: 'video',
part: 'snippet',
q: '백현'
}
}).then((response) => {
this.videos = response.data.items
this.selectedVideo = this.videos[0]
}).catch((error) => {
console.error(error)
})
},
data() {
return {
videos: [],
selectedVideo: {}
}
},
computed: {
videoSrc() {
// return `http://www.youtube.com/embed/${this.selectedVideo.id.videoId}`
const url = 'http://www.youtube.com/embed/'
return url + this.selectedVideo.id.videoId
},
isSelecedVideo() {
// 길이가 1 이상이면 True
return !!Object.keys(this.selectedVideo).length
}
}
}
</script>
<style>
* {
font-family: 'Noto Sans KR', sans-serif;
}
.video-title {
border: 1px solid gray;
}
</style>
|
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
template="/templates/default.xhtml">
<ui:define name="content">
<f:metadata>
<f:viewParam name="id" value="#{forgottenPasswordController.id}"></f:viewParam>
<f:viewAction action="#{forgottenPasswordController.checkId}" ></f:viewAction>
</f:metadata>
<h:form rendered="#{!forgottenPasswordController.validId}">
<p:panel header="Request Password Reset link">
<p>Enter the user name for the account you wish to have the password reset.</p>
<p>The password reset link is sent to the email associated with the user account.</p>
<h:panelGrid columns="1">
<p:outputLabel for="userName" value="User Name"></p:outputLabel>
<p:inputText id="userName" value="#{forgottenPasswordController.accountName}" requiredMessage="true"></p:inputText>
</h:panelGrid>
</p:panel>
<p:commandButton value="Get Link" action="#{forgottenPasswordController.requestPasswordResetToken}" ajax="no"></p:commandButton>
</h:form>
<h:form rendered="#{forgottenPasswordController.validId}">
<p:panel header="Password Reset">
<p>Choose a strong password!</p>
<h:panelGrid columns="1">
<p:outputLabel for="password" value="Password"></p:outputLabel>
<p:password id="password" value="#{forgottenPasswordController.password.password}" redisplay="true" match="confirmPass" required="true"></p:password>
<p:outputLabel for="confirmPass" value="Confirm Password"></p:outputLabel>
<p:password id="confirmPass" value="#{forgottenPasswordController.password.confirmPassword}" redisplay="true" required="true"></p:password>
</h:panelGrid>
</p:panel>
<p:commandButton action="#{forgottenPasswordController.reset}" value="Reset Password" ajax="no">
<f:param name="id" value="#{forgottenPasswordController.id}"></f:param>
</p:commandButton>
</h:form>
</ui:define>
</ui:composition>
|
import { assert, assertEquals } from "./test_deps.ts";
import { DataFactory, type RDF } from "ldkit/rdf";
import { BindingsFactory, QuadFactory, RDFJSON } from "../library/rdf.ts";
Deno.test("RDF / Quad Factory", () => {
const df = new DataFactory();
const quadFactory = new QuadFactory(df);
const q = (s: string, p: string, o: RDF.Quad_Object) => {
return df.quad(df.namedNode(s), df.namedNode(p), o);
};
const equalQuads = (triple: RDFJSON.Triple, quad: RDF.Quad) => {
const createdQuad = quadFactory.fromJson(triple);
assertEquals(createdQuad, quad);
};
equalQuads(
["s", "p", { type: "literal", value: "o" }],
q("s", "p", df.literal("o")),
);
equalQuads(
["s", "p", { type: "uri", value: "o" }],
q("s", "p", df.namedNode("o")),
);
});
Deno.test("RDF / Bindings Factory", () => {
const df = new DataFactory();
const bindingsFactory = new BindingsFactory(df);
const equalBindings = (
jsonBindings: RDFJSON.Bindings,
bindingsEntries: [string, RDF.Term][],
) => {
const createdBindings = bindingsFactory.fromJson(jsonBindings);
const bindings = new Map(bindingsEntries);
assertEquals(createdBindings.size, bindings.size);
bindings.forEach((term, variable) => {
assert(createdBindings.has(variable));
assertEquals(term, createdBindings.get(variable));
assertEquals(term, createdBindings.get(df.variable(variable)));
});
createdBindings.forEach((term, variable) => {
assertEquals(term, bindings.get(variable.value));
});
};
equalBindings(
{
"var": { type: "literal", value: "v" },
},
[
["var", df.literal("v")],
],
);
});
|
//
// MapPresenter.swift
// SevenWindsCoffee
//
// Created by Mark Golubev on 10/02/2024.
//
import Foundation
protocol MapPresenterProtocol {
var router: MapRouterProtocol? {get set}
var interactor: MapInteractorPtotocol? {get set}
var view: MapViewProtocol? {get set}
func fetchCoffeeShops()
func fetchSuccess(shops: CoffeeShopsEntity)
func fetchError(message: String)
func unauthorisedUser()
func tapOnPlacemark(id: Int)
var shops: CoffeeShopsEntity { get set }
}
class MapPresenter: MapPresenterProtocol, MapInteractorOutputProtocol {
var router: MapRouterProtocol?
var interactor: MapInteractorPtotocol?
var view: MapViewProtocol?
var shops: CoffeeShopsEntity = []
func fetchCoffeeShops() {
guard let token = KeychainHelper.shared.getCredentials() else { return }
interactor?.fetchData(token: token)
}
func fetchSuccess(shops: [CoffeeShopsEntityElement]) {
self.shops = shops
view?.fetchShopSuccess()
}
func tapOnPlacemark(id: Int) {
router?.navigateToMenu(id: id)
}
func fetchError(message: String) {
view?.showFetchError(message: message)
}
func unauthorisedUser() {
view?.unauthorisedUser()
}
}
|
# more feature engineering
mws <- textstat_readability(train$discourse_text,
measure = "meanWordSyllables")
train <- cbind(train, mws)
train %>%
tibble() %>%
select(-document) -> train
# more feature engineering
msl <- textstat_readability(train$discourse_text,
measure = "meanSentenceLength")
train <- cbind(train, msl)
train %>%
tibble() %>%
select(-document) -> train
# more feature engineering
ws <- textstat_readability(train$discourse_text,
measure = "Wheeler.Smith")
train <- cbind(train, ws)
train %>%
tibble() %>%
select(-document) -> train
# more feature engineering
sp <- textstat_readability(train$discourse_text,
measure = "Spache")
train <- cbind(train, sp)
train %>%
tibble() %>%
select(-document) -> train
# more feature engineering
rix <- textstat_readability(train$discourse_text,
measure = "RIX")
train <- cbind(train, rix)
train %>%
tibble() %>%
select(-document) -> train
# more feature engineering
nws <- textstat_readability(train$discourse_text,
measure = "nWS")
train <- cbind(train, nws)
colnames(train)
train %>%
tibble() %>%
select(-document) -> train
#-------------z
library(tidymodels)
ssplit <- initial_split(train,
strata = discourse_type)
ttrain <- training(ssplit)
ttest <- testing(ssplit)
ttrain %>%
mutate(c_grade = floor(colman_grade)) -> ttrain
ttest %>%
mutate(c_grade = floor(colman_grade)) -> ttest
summary(ttrain)
ttrain %>%
count(discourse_type, sort = TRUE) %>%
select(n, discourse_type)
ttrain %>%
group_by(flesch) %>%
tally
#---------- not sure this help more than to overfit
library(tidylo)
max_log_odds <- function (df) {
df %>%
tibble %>%
select(flesch,
discourse_type,
discourse_text) %>%
mutate(flesch_ceiling = ceiling(flesch)) %>%
rowid_to_column() %>%
unnest_tokens(words,
discourse_text) %>%
count(discourse_type,
flesch_ceiling,
words,
sort = TRUE) %>%
bind_log_odds(flesch_ceiling,
words, n) %>%
group_by(flesch_ceiling,
discourse_type) %>%
arrange(-log_odds_weighted) %>%
slice_head(n = 20) %>%
ungroup() %>%
select(-n) %>%
pivot_wider(
names_from = words,
values_from = log_odds_weighted
) %>%
replace(is.na(.),0)
}
max_log_odds(ttrain) -> log_df
log_df %>%
tibble %>%
head(20)
ttrain %>%
mutate(flesch_ceiling = ceiling(flesch)) %>%
left_join(log_df,
by = c("flesch_ceiling",
"discourse_type")) %>%
tibble -> ttrain
#-----------
add <- function (df, var) {
df %>%
rename({{ var }} := mean_logs) %>%
tibble
}
add(new_data, c_log)
#------------ this is the best function but not used
l_odds <- function (df, var, var1) {
df %>%
as_tibble() %>%
select({{ var }},
discourse_type,
discourse_text) %>%
rowid_to_column() %>%
unnest_tokens(words,
discourse_text) %>%
count({{ var }},
discourse_type,
words,
sort = TRUE) %>%
bind_log_odds({{ var }}, words, n) %>%
group_by({{ var }}, discourse_type) %>%
mutate(mean_logs= min(log_odds_weighted)) %>%
select(-n, -log_odds_weighted, -words) %>%
unique() %>%
rename({{ var1 }} := mean_logs) %>%
tibble
}
l_odds(ttrain,
c_grade,
c_logs) -> new_data
ttrain %>%
left_join(new_data,
by = c("c_grade",
"discourse_type")) -> ttrain
l_odds(ttrain,
mean,
f_logs) -> new_data
ttrain %>%
left_join(new_data,
by = c("mean",
"discourse_type")) -> ttrain
colnames(ttrain)
ttrain[sapply(ttrain, is.infinite)] <- 0
sum(is.infinite(ttrain$c_logs))
#----- endo of logs odds
colnames(ttrain)
#---------
tthree_rec <-
recipe( ~
hapax +
TTR +
flesch +
mean +
grade_no +
fleisch_type +
colman_grade +
scrabble_score +
smog_score +
entropy +
c_grade +
nWS +
Spache +
Wheeler.Smith +
meanSentenceLength +
meanWordSyllables +
RIX +
discourse_text,
data = ttrain) %>%
step_tokenize(discourse_text) %>%
step_tokenfilter(discourse_text,
max_tokens = 10000) %>%
step_lda(discourse_text)
prepped_tthree_rec <- prep(tthree_rec)
prepped_tthree_rec_matrix <- bake(prepped_tthree_rec,
new_data = NULL,
composition = "matrix")
dim(prepped_tthree_rec_matrix)
#----- model
cnn_mod <- keras_model_sequential()
cnn_mod %>%
layer_conv_1d(filters = 64,
kernel_size = 3,
strides = 1,
activation = 'relu',
input_shape = c(27, 1)) %>%
layer_conv_1d(filters = 64,
kernel_size = 3,
activation = 'relu') %>%
layer_max_pooling_1d(pool_size = 3) %>%
layer_conv_1d(filters = 128,
kernel_size = 3,
activation = 'relu') %>%
layer_conv_1d(filters = 128,
kernel_size = 3,
activation = 'relu') %>%
layer_global_average_pooling_1d() %>%
layer_dropout(rate = 0.4) %>%
layer_dense(units = 128, activation = 'relu') %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 36, activation = 'relu') %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 7, activation = 'softmax')
cnn_mod
cnn_mod %>% compile(
loss = 'categorical_crossentropy',
optimizer = optimizer_adam(),
metrics = metric_auc(multi_label = TRUE)
)
ttrain %>%
mutate(discourse_type = as.factor(discourse_type),
labels = as.numeric(discourse_type)) -> ttrain_label
y_train = keras::to_categorical(ttrain_label$labels-1)
y_train %>%
head()
third_his <- cnn_mod %>%
fit(
prepped_tthree_rec_matrix,
y_train,
epochs = 20,
validation_split = 0.1,
batch_size = 512,
)
third_his
#----------
ttest %>%
select(discourse_type) %>%
mutate(discourse_type = as.factor(discourse_type),
labels = as.numeric(discourse_type)) -> ttest_labels
y_true= keras::to_categorical(ttest_labels$labels-1)
l_odds(ttest, c_grade, c_logs) -> new_data
ttest %>%
left_join(new_data, by = c("c_grade", "discourse_type")) -> ttest
l_odds(ttest, mean, f_logs) -> new_data
ttest %>%
left_join(new_data, by = c("mean", "discourse_type")) -> ttest
colnames(ttest)
ttest[sapply(ttest, is.infinite)] <- 0
sum(is.infinite(ttest$c_logs))
tthree_test <- bake(prepped_tthree_rec,
new_data = ttest,
composition = "matrix")
cnn_mod %>% evaluate(tthree_test, y_true) # 50 auc
cnn_mod %>% predict(tthree_test) %>% k_argmax() -> arrays # not sure about this
arrays %>%
as.array() %>%
tibble %>%
as.data.frame.table() %>%
select(-Var1, -Var2) ->arrays
colnames(arrays) <- "preds"
arrays %>%
mutate(preds = preds + 1) -> arrays
arrays %>%
mutate(preds = as.factor(preds)) %>%
group_by(preds) %>%
tally
cnn_three_test %>%
group_by(discourse_type) %>%
tally
arrays %>%
bind_cols(cnn_test_labels) %>%
tibble %>%
group_by(discourse_type, labels, preds) %>%
tally %>% View
arrays %>%
bind_cols(cnn_test_labels) %>%
tibble %>%
mutate(across(everything(), factor)) -> new_arrays
levels(new_arrays$preds)
new_arrays$preds <- factor(new_arrays$preds, levels = c(levels(new_arrays$preds), "6"))
new_arrays$preds <- factor(new_arrays$preds, levels = c("1", "2", "3", "4", "5", "6", "7"))
new_arrays %>%
conf_mat(labels, preds) %>%
autoplot(type = "heatmap")
|
# Threat Intelligence
# Nmap
```bash
nmap –help
PORT SPECIFICATION AND SCAN ORDER:
-p : Only scan specified ports
Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
–exclude-ports : Exclude the specified ports from scanning
-F: Fast mode – Scan fewer ports than the default scan
-r: Scan ports consecutively – don’t randomize
–top-ports : Scan most common ports
–port-ratio : Scan ports more common
```
# IP Address Decoy
IP address decoy technique refers to generating or manually specifying the IP addresses of decoys in order to evade an IDS or firewall.
`Nmap -D RND:10 <target IP address>`
# PKI
- PKI are use verify and authenticate the identity of individuals within the enterprise
# Common Port
- 113 port is used for Identification / Authorization service, TCP and UDP
- 69 port is Trivial File Transfer Protocol (TFTP), UDP
- 161 port Simple Network Management Protocol (SNMP), TCP and UDP
- 123 port NTP
- ftp (port 21), option A. telnet (port 23) is not used for file transfer and ssh (port 22) is encrypted.
# Port 161
- Port 161 Details. Simple network management protocol (SNMP). Used by various devices and applications (including firewalls and routers) to communicate logging and management information with remote monitoring applications.
- SNMP run on the UDP 161, and Secure Version is SNMPv3.
# Port 389
- TCP/UDP 389: Lightweight Directory Access Protocol (LDAP), LDAPS (LDAP over SSL) 636. (P.414/398)
# TCP/UDP 445: SMB over TCP (Direct Host)
Windows supports file- and printer-sharing traffic using the SMB protocol directly hosted on TCP. (P.413/397)
# Conducting Location Search on Social Media Sites
Such as Twitter, Instagram, and Facebook helps attackers to detect the geolocation of the target. This information further helps attackers to perform various social engineering and non-technical attacks.
Many online tools such as `Followerwonk`, `Hootsuite`, and `Sysomos` are available to search for both geotagged and non-geotagged information on social media sites. (P.183/167)
- HootSuite Enterprise provides geo-location and targeting functionality that give you insight into web traffic while driving customers to your door. Use location and language targeting to engage with your specific audience
# Vuln Scan
- Vulnerability Assessment Tools:
Qualys / Nessus / OpenVAS / Nikto / Nexpose
- Nikto is an Open Source (GPL) web server scanner that performs comprehensive tests against web servers for multiple items, including over 6 700 potentially dangerous files or programs, checks for outdated versions of over 1250 servers, and checks for version specific problems on over 270 servers.
# Type of Scanner
1. `Network-Based Scanner`: Network-based scanners are those that interact only with the real machine where they reside and give the report to the same machine after scanning.
2. `Agent-Based Scanner`: Agent-based scanners reside on a single machine but can scan several machines on the same network. Agent-based scanners make use of software scanners on each and every device; the results of the scans are reported back to the central server. Such scanners are well equipped to find and report out on a range of vulnerabilities
3. `Proxy Scanner`: Proxy scanners are the network-based scanners that can scan networks from any machine on the network.
4. `Cluster scanner`: Cluster scanners are similar to proxy scanners, but they can simultaneously perform two or more scans on different machines in the network.
# Web Application Threats
- OWASP Top 10 Application Security Risks
Security Misconfiguration - Parameter/Form Tampering
- A web parameter tampering attack involves the manipulation of parameters exchanged between the client and the server to modify application data such as user credentials and permissions.
- This information is actually stored in cookies, hidden form fields, or URL query strings. (P.1770/1754)
# host command
- `host -t a hackeddomain.com`
With option "-t" you can specify the type of the DNS request.
# Security and Privacy Control
- NIST-800-53
The National Institute of Standards and Technology (NIST), within the U.S. Department of Commerce, creates standards and guidelines pertaining to information security.
NIST 800-53 mandates specific security and privacy controls required for federal government and critical infrastructure.
https://cloud.google.com/security/compliance/nist800-53/
# Scanning and footprinting
- Passive OS fingerprinting involves sniffing network traffic at any given collection point and matching known patterns that pass to a table of pre-established OS identities. No traffic is sent with passive fingerprinting.
Nmap does not use a passive style of fingerprinting. Instead it performs its Operating System Fingerprinting Scan (OSFS) via active methodologies.
- By observing specific characteristics of the packets, such as the Time To Live (TTL) value or specific flags, an analyst can infer information about the operating system of the device sending those packets. This process is passive because it doesn't require direct interaction with the target system, as the information is collected by simply monitoring the network traffic.
- OS Discovery/Banner Grabbing
Passive Banner Grabbing
Sniffing the network traffic - Capturing and analyzing packets from the target
- `(traceroute) and ping commands can't OS fingerprinting`
# Virus and Malware
- A boot sector virus is a type of virus that infects `the boot sector of floppy disks or the primary boot record of hard disks` (some infect the boot sector of the hard disk instead of the primary boot record). The infected code runs when the system is booted from an infected disk, but once loaded it will infect other floppy disks when accessed in the infected computer. While **boot sector viruses infect at a BIOS level**, they use DOS commands to spread to other floppy disks. For this reason, they started to fade from the scene after the appearance of Windows 95 (which made little use of DOS instructions). Today, there are programs known as ‘bootkits’ that write their code to the primary boot record as a means of loading early in the boot process and then concealing the actions of malware running under Windows. However, they are not designed to infect removable media.
The only absolute criteria for a boot sector is that it must contain 0x55 and 0xAA as its last two bytes. If this signature is not present or is corrupted, the computer may display an error message and refuse to boot. Problems with the sector may be due to physical drive corruption or the presence of a boot sector virus.
```
According to EC-Council Module07 Page 919
A boot sector virus moves MBR to another location on the hard disk and copies itself to the original location of MBR. When the system boots, first, the code executes and the control passes to the original MBR.
```
# Mulitpartite virus
- A multipartite virus is a fast-moving virus that uses file infectors or boot infectors to attack the boot sector and executable files
simultaneously.
- A multipartite virus (also known as a multipart virus or hybrid virus) combines the approach of file infectors and boot record infectors and attempts to `simultaneously` attack both the boot sector and the executable or program files
# Polymorphic virus
- Polymorphic viruses rely on mutation engines to alter their decryption routines every time they infect a machine. This way, traditional security solutions may not easily catch them because they do not use a static, unchanging code. The use of complex mutation engines that generate billions of decryption routines make them even more difficult to detect.
- They are designed to change their appearance or signature files to avoid detection by traditional antivirus software, which scans for specific files and looks for specific patterns. A polymorphic virus will continue changing its file names and physical location — not only after each infection, but as often as every 10 minutes
- URSNIF, VIRLOCK, VOBFUS, and BAGLE or UPolyX are some of the most notorious polymorphic viruses in existence
# Steath virus
- a stealth virus is a computer virus that uses various mechanisms to avoid detection by antivirus software. Generally, stealth describes any approach to doing something while avoiding notice
- The question includes: "can change its own code". `Encryption does nothing with the virus code`. It just encrypts it, and after some trigger decrypts it and the virus runs. Change of the key does nothing to the source code of virus, just changes the "presentation" form in encrypted state. I will definitely go with Poly/MetaMorphic ones but with provided answers Stealth fits better.
- `Stealth virus`: change its code + cipher ( this is way is called STEALTH, to avoid being detected)
`Encription virus`: cipher ( only cipher to avoid being detected)
- `A stealth virus` usually enters the system via infected web links, malicious email attachments, third-party application downloads, etc. The virus tricks the system to get past an antivirus program using two primary methods:
1. Code modification. To avoid detection, the virus modifies the code and virus signature of every infected file.
2. Data encryption. The virus renders the affected file inaccessible or unreadable to the user by encrypting it and also by using a different encryption key for different files.
Therefore answer is Stealth virus
# Encryption virus
- Encryption virus is just another name for Ransomware, as it encrypts the victim's files and folders.
# Fileless Malware
- Fileless Malware
Fileless malware can easily evade various security controls, organizations need to focus on monitoring, detecting, and preventing malicious activities instead of using traditional approaches such as scanning for malware through file signatures.Also known as non-malware, infects legitimate software, applications, and other protocols existing in the system to perform various malicious activities.It resides in the system’s RAM. It injects malicious code into the running processes
- bypass the company's application whitelisting
# Botnet Trojans
- They trick regular computer users into downloading Trojan-infected files to their systems through phishing, SEO hacking, URL redirection, etc. Once the user downloads and executes this botnet Trojan in the system, it connects back to the attacker using IRC channels and waits for further instructions.They help an attacker to launch various attacks and perform nefarious activities such as DoS attacks, spamming, click fraud, and theft of application serial numbers, login IDs, and credit card numbers. (P.886/870),`"coordinated attack" is the clue`
# Credential enumerator
- is a self-extracting RAR file containing two components: a `bypass component` and a `service component`.
- The bypass component is used for the enumeration of network resources and either finds writable share drives using Server Message Block (SMB) or tries to brute force user accounts, including the administrator account.
- Once an available system is found, Emotet writes the service component on the system, which writes Emotet onto the disk. `Emotet’s access to SMB` can result in the infection of entire domains (servers and clients).
# Scareware
- Scareware is a type of malware that tricks computer users into visiting malware-infested websites or downloading or buying potentially malicious software. Scareware is often seen in pop-ups that tell the target user that their machine has been infected with malware. Further, these pop-up ads always have a sense of urgency. (P.1237/1221)
## Security administrator John Smith has noticed abnormal amounts of traffic coming from local computers at night. Upon reviewing, he finds that user data have been exfiltrated by an attacker. AV tools are unable to find any malicious software, and the IDS/IPS has not reported on any non-whitelisted programs.
What type of malware did the attacker use to bypass the company's application whitelisting?
A. File-less malware (Correct Answer)
B. Zero-day malware
C. Phishing malware
D. Logic bomb malware
# Sniffing
- Ethereal has a very good `graphical user interface`, can provide information on packet
- tcpdump is a common packet analyzer that runs under the `command line`
# DHCP snooping
- DHCP snooping is a security feature that acts like a firewall between untrusted hosts and trusted DHCP servers. The DHCP snooping feature performs the following activities:
>- Validates DHCP messages received from untrusted sources and filters out invalid messages. •
## Overview of Dynamic ARP Inspection
- Dynamic ARP Inspection (DAI) is a security feature that validates Address Resolution Protocol (ARP) packets in a network. DAI allows a network administrator to intercept, log, and discard ARP packets with invalid MAC address to IP address bindings. This capability protects the network from certain “man-in-the-middle” attacks.
- Defend Against ARP Poisoning
Implement Dynamic ARP Inspection(DAI) Using DHCP Snooping Binding Table.
- To validate the ARP packet, the DAI performs IP-address-to-MAC-address binding inspection stored in the DHCP snooping database before forwarding the packet to its destination. If any invalid IP address binds a MAC address, the DAI will discard the ARP packet. (P.1149/1133)
# Bob, a network administrator at BigUniversity, realized that some students are connecting their notebooks in the wired network to have Internet access. In the university campus, there are many Ethernet ports available for professors and authorized visitors but not for students. He identified this when the IDS alerted for malware activities in the network.
What should Bob do to avoid this problem?
A. Disable unused ports in the switches
B. Separate students in a different VLAN
C. Use the 802.1x protocol
D. Ask students to use the wireless network
# Answer is C `use 802.1x` prtocol
- How does 802.1X work?
802.1X is a network authentication protocol that opens ports for network access when an organization `authenticates a user’s identity and authorizes them for access to the network`. The user’s identity is determined based on their credentials or certificate, which is confirmed by the RADIUS server. The RADIUS server is able to do this by communicating with the organization’s directory, typically over the LDAP or SAML protocol.
- A is not possible, because if you disable the ports they cannot be used by teachers or authorized visitors. Answer C is correct, as this protocol requires users to authenticate to validate whether they have permissions to use the network or not.
# Fuzzing
- Attackers use the fuzzing technique to repeatedly send random input to the target API to generate error messages that reveal critical information.
- To perform fuzzing, attackers use automated scripts that send a huge number of requests with a varying combination of input parameters to achieve the goal
# Protocol Analyzer (eg. Wireshark)
- A protocol analyzer is a tool (hardware or software) used to capture and analyze signals and data traffic over a communication channel.
Purpose is to monitor network usage and identify malicious network traffic generated by hacking software installed on the network.
- You can use a sniffer to create a pcap file but you need a protocol analyzer. An example of a protocol analyzer is WireShark which you can clearly use to analyze a pcap file.
- Sniffer in general can be used only to capture the traffic. Protocol analyser is need to read the capture, parse it properly and provide you easy way to read the content.
- The confusion is that the most well known tool - Wireshark can do both, but those are two different roles.
# Heartbleed
- The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptographic software library. This weakness allows stealing the information protected, under normal conditions, by the SSL/TLS encryption used to secure the Internet.
- This compromises the secret keys used to identify the service providers and to encrypt the traffic, the names and passwords of the users and the actual content.
- The data obtained by a Heartbleed attack may include unencrypted exchanges between TLS parties likely to be confidential, including any form post data in users’ requests.
- Moreover, the confidential data exposed could include authentication secrets such as session cookies and passwords, which might allow attackers to impersonate a user of the service.An attack may also reveal private keys of compromised parties
# Risk accessment
#### Apparently there 4 Critical Components of an Effective Risk Assessment. They are:
-Technical Safeguards
-Organisational Safeguards
-Physical Safeguards
-Administrative Safeguards
Src: https://www.digirad.com/four-critical-components-effective-risk-assessment/
- The `HIPAA Security Rule` establishes national standards to protect individuals’ electronic personal health information that is created, received, used, or maintained by a covered entity. The Security Rule requires appropriate `administrative`, `physical`, and `technical` safeguards to ensure the confidentiality, integrity, and security of electronically protected health information. CEHv11 book page 97 (81)
# Email spoofing
- `Email spoofing` is the creation of email messages with a forged sender address to make it look like a valid employee of the company, for example.
- `Masquerading` is when you spoof the mail and modify the content to look like a legitimate mail.
The mail protection system can detect a spoofed sender, but not a masqueraded content. It should block the spoofed sender.
# Bob, a system administrator at TPNQM SA, concluded one day that a DMZ is not needed if he properly configures the firewall to allow access just to servers/ports, which can have direct internet access, and block the access to workstations. Bob also concluded that DMZ makes sense just when a stateful firewall is available, which is not the case of TPNQM SA.
In this context, what can you say?
A. Bob can be right since DMZ does not make sense when combined with stateless firewalls
B. Bob is partially right. He does not need to separate networks if he can create rules by destination IPs, one by one
C. Bob is totally wrong. DMZ is always relevant when the company has internet servers and workstations Most Voted
D. Bob is partially right. DMZ does not make sense when a stateless firewall is available
- CEH chapter9, Perimeter Defense Mechanisms
## Answer is `B`
# SMTP Server
SMTP provides 3 built-in-commands:
1. VRFY - Validates users
2. EXPN - Shows the actual delivery addresses of aliases and mailing lists
3. RCPT TO - Defines the recipients of a message
- According to your source Verify (VRFY) and Expand (EXPN) do the same thing. Upon further research it seems that VRFY is used to verify an (email) address and EXPN is used to determine the membership of a mailing list
# Infoga
- Infoga is a free and open-source tool, which is used for finding if emails were leaked using haveibeenpwned.com API. Infoga is used for scanning email addresses using different websites and search engines for information gathering and finding information about leaked information on websites and web apps.
- mail tracking tools allow an attacker to collect information such as IP addresses, mail servers, and service providers involved in sending the email. Attackers can use this information to build a hacking strategy and to perform social engineering and other attacks. Examples of email tracking tools include eMailTrackerPro, Infoga, and Mailtrack.
# IOT
- Information Gathering using FCC ID Search
FCC ID Search helps in finding the details and granted certification of the devices.
- FCC ID contains two elements:
1. Grantee ID (initial three or five characters) and
2. Product ID (remaining characters).
- Attackers can gather basic information about a target device using FCC ID Search available on https://www.fcc.gov/oet/ea/fccid
Using this information, an attacker can find underlying vulnerabilities in the target device and launch further attacks.
- FCC ID Search can be used to look up detailed information on the device if an FCC identification number is printed on the board (or found otherwise). This search will return information on the manufacturer, model, and chipset
# What is the port to block first in case you are suspicious that an IoT device has been compromised?
## ANS = Port 48101
- How to Defend Against IoT Hacking
Mirai, look for suspicious traffic on port 48101. Infected devices often attempt to spread malware by using port 48101 to send results to the threat actor.Monitor traffic on port 48101 as infected devices attempt to spread malicious file
- IOT Uses port 48101 and that is the port to monitor for potential issues then closing that port will stop IOT from communication with the network
- The question is incorrect, it is not about knowledge of the IoT security concept, but about knowledge of one of the largest DDos attacks using Mirai in 2016:
- On September 20, 2016, Brian Krebs’ security blog (krebsonsecurity.com) was targeted by a massive DDoS attack, one of the largest on record, exceeding 620 gigabits per second (Gbps). An IoT botnet powered by Mirai malware created the DDoS attack. The Mirai malware continuously scans the Internet for vulnerable IoT devices, which are then infected and used in botnet attacks. The Mirai bot uses a short list of 62 common default usernames and passwords to scan for vulnerable devices. Because many IoT devices are unsecured or weakly secured, this short dictionary allows the bot to access hundreds of thousands of devices.
- And one of Preventive Steps was:
- Look for suspicious traffic on port 48101. Infected devices often attempt to spread malware by using port 48101 to send results to the threat actor.
# Docker
- The Docker daemon (dockerd) listens for Docker API requests and manages Docker objects such as images, containers, networks, and volumes. A daemon can also communicate with other daemons to manage Docker services
# You are a penetration tester working to test the user awareness of the employees of the client XYZ. You harvested two employees' emails from some public sources and are creating a client-side backdoor to send it to the employees via email.
Which stage of the cyber kill chain are you at?
A. Reconnaissance
B. Weaponization Most Voted
C. Command and control
D. Exploitation
## Ans - D (Exploitation)
- I feel the correct answer is weaponization (B) and not Exploitation (D). Question clearly states that the tester is "creating" the backdoor. It hasn't been sent to the victim yet. So recon was done, weaponization is next, then deliver via email (which is not yet done) and then exploitation. Thoughts?
# CVSS Score
```
Maybe this is a bit clearer?
Rating CVSS Score
None 0.0
Low 0.1 - 3.9
Medium 4.0 - 6.9
High 7.0 - 8.9
Critical 9.0 - 10.0
```
# Samuel, a security administrator, is assessing the configuration of a web server. He noticed that the server permits SSLv2 connections, and the same private key certificate is used on a different server that allows SSLv2 connections. This vulnerability makes the web server vulnerable to attacks as the SSLv2 server can leak key information.
Which of the following attacks can be performed by exploiting the above vulnerability?
A. Padding oracle attack
B. DROWN attack
C. DUHK attack
D. Side-channel attack
## ANS = B (DROWN attack)
# DROWN Attack
- DROWN attack allows an attacker to decrypt intercepted TLS connections by making specially crafted connections to an SSLv2 server that uses the same private key.
- The DROWN (Decrypting RSA with Obsolete and Weakened eNcryption) attack is a cross-protocol security bug that attacks servers supporting modern SSLv3/TLS protocol suites by using their support for the obsolete, insecure, SSL v2 protocol to leverage an attack on connections using up-to-date protocols that would otherwise be secure.[1][2] DROWN can affect all types of servers that offer services encrypted with SSLv3/TLS yet still support SSLv2, provided they share the same public key credentials between the two protocols.[3] Additionally, if the same public key certificate is used on a different server that supports SSLv2, the TLS server is also vulnerable due to the SSLv2 server leaking key information that can be used against the TLS server.
- A DROWN attack is a cross-protocol weakness that can communicate and initiate an attack on servers that support recent SSLv3/TLS protocol suites. A DROWN attack makes the attacker decrypt the latest TLS connection between the victim client and server by launching malicious SSLv2 probes using the same private key
# DUHK attack??
# LDAP enumeration
- Attackers can enumerate information such as valid usernames, addresses, and departmental details from different LDAP servers. Ex: Active Directory Explorer(AD Explorer)、JXplorer (P.439/423)
# ohnson, an attacker, performed online research for the contact details of reputed cybersecurity firms. He found the contact number of sibertech.org and dialed the number, claiming himself to represent a technical support team from a vendor. He warned that a specific server is about to be compromised and requested sibertech.org to follow the provided instructions. Consequently, he prompted the victim to execute unusual commands and install malicious files, which were then used to collect and pass critical information to Johnson's machine.
What is the social engineering technique Steve employed in the above scenario?
A. Diversion theft
B. Quid pro quo Most Voted
C. Elicitation
D. Phishing
## Ans - C (Elicitation)
- In summary, quid pro quo involves an exchange of something valuable for information or access, while elicitation involves questioning techniques to obtain information from the victim without an exchange of something valuable.
- Elicitation is a structured method of communication used to extract predetermined information from people without making them aware that they are a collection target. here the keyword is Collect which is used in the question
- This doesn't seem a Quid pro quo, because nothing is offered for something else
- Answer is elicitation. The person is calling pretenting to be someone they are not and eliciting information.
It is not B. Quid Pro Quo. This is 'something for something.' The attacker is not offering anything. They are demanding help under the guise of being someone else
- "quid pro quo" is explained in the CEH books as follows "Attackers call numerous random numbers within a company, claiming to be from technical support They offer their service to end users in exchange for confidential data or login credentials"
# To create a botnet, the attacker can use several techniques to scan vulnerable machines. The attacker first collects information about a large number of vulnerable machines to create a list. Subsequently, they infect the machines. The list is divided by assigning half of the list to the newly compromised machines.
The scanning process runs simultaneously. This technique ensures the spreading and installation of malicious code in little time.
Which technique is discussed here?
A. Subnet scanning technique
B. Permutation scanning technique
C. Hit-list scanning technique. Most Voted
D. Topological scanning technique
## Ans - D (Topological Scanning)
- Random Scanning - The infected machine probes IP addresses randomly from the target network IP range and checks for vulnerabilities
- Hit-list Scanning - An attacker first collects a list of potentially vulnerable machines and then scans them to find vulnerable machines
- Topological Scanning - It uses information obtained from an infected machine to find new vulnerable machines
- Local Subnet Scanning - The infected machine looks for new vulnerable machines in its own local network
- Permutation Scanning - It uses a pseudorandom permutation list of IP addresses to find new vulnerable machines
# An organization is performing a vulnerability assessment for mitigating threats. James, a pen tester, scanned the organization by building an inventory of the protocols found on the organization's machines to detect which ports are attached to services such as an email server, a web server, or a database server. After identifying the services, he selected the vulnerabilities on each machine and started executing only the relevant tests.
What is the type of vulnerability assessment solution that James employed in the above scenario?
A. Service-based solutions
B. Product-based solutions
C. Tree-based assessment
D. Inference-based assessment Most Voted
## ANS - D (Inference-based assessment)
- In an inference-based assessment, scanning starts by building an inventory of the
protocols found on the machine. After finding a protocol, the scanning process starts to detect which ports are attached to services, such as an email server, web server, or database server. After finding services, it selects vulnerabilities on each machine and starts to execute only those relevant tests
## Product based solution vs Service based solution
- Product based solutions are deployed within the network. Usually dedicated for internal network.
- Service based solutions are third-party solutions which offers security and auditing. This can be host either inside or outside the network. This can be a security risk of being compromised.
## Tree-based Assessment vs Inference-based Assessment
- Tree-based Assessment is the approach in which auditor follows different strategies for each component of an environment
- Inference-based Assessment is the approach to assist depending on the inventory of protocols in an environment
# Host-based assessments
- are a type of security check that involve conducting a `configuration-level check` to identify system configurations, user directories, file systems, registry settings, and other parameters to evaluate the possibility of compromise.
- Host-based scanners assess systems to identify vulnerabilities such as `native configuration tables, incorrect registry or file permissions, and software configuration errors`. (P.528/512)
# .bash_history
- The SMB command uses the password to perform the login, this is stored in the bash_history. However, a log (xsession-log) never saves the credentials in its records.
# Robots.txt
- Information Gathering from Robots.txt File A website owner creates a robots.txt file to list the files or directories a web crawler should index for providing search results. Poorly written robots.txt files can cause the complete indexing of website files and directories. If confidential files and directories are indexed, an attacker may easily obtain information such as passwords, email addresses, hidden links, and membership areas. If the owner of the target website writes the robots.txt file without allowing the indexing of restricted pages for providing search results, an attacker can still view the robots.txt file of the site to discover restricted files and then view them to gather information. An attacker types URL/robots.txt in the address bar of a browser to view the target website’s robots.txt file. An attacker can also download the robots.txt file of a target website using the Wget tool.
Certified Ethical Hacker(CEH) Version 11 pg 1650
# Cloud Deployment Model
1. Community Cloud
Shared infrastructure between several organizations from a specific community with common concerns (security, compliance, jurisdiction, etc.) (P.2817/2801)
2. Public Cloud: In the public cloud model, cloud resources are owned and operated by a third-party service provider. These resources are made available to the general public or a large user base over the internet. Users can access and utilize computing resources, storage, and applications on a pay-per-use basis. Examples of public cloud providers include Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP).
2. Private Cloud: A private cloud is dedicated to a single organization or entity. It can be owned, managed, and operated by the organization itself or a third-party provider exclusively for that organization. Private clouds offer increased control, security, and customization options compared to public clouds. They can be located on-premises, within the organization's data center, or hosted off-site.
3. Hybrid Cloud: The hybrid cloud model combines elements of both public and private clouds. It allows organizations to integrate their on-premises infrastructure with public cloud services. This enables businesses to maintain control over sensitive data and critical workloads in a private cloud while taking advantage of the scalability and flexibility offered by the public cloud for less sensitive or variable workloads. Hybrid clouds provide a balance between security, control, and cost-effectiveness.
# Andrew is an Ethical Hacker who was assigned the task of discovering all the active devices `hidden by a restrictive firewall` in the IPv4 range in a given target network.
Which of the following host discovery techniques must he use to perform the given task?
A. UDP scan
B. ARP ping scan Most Voted
C. ACK flag probe scan
D. TCP Maimon scan
## Ans - C (ACK flag probe scan)
- " hidden by a restrictive firewall " so is will not by ARP, but ACK flag.
# An organization has automated the operation of critical infrastructure from a remote location. For this purpose, all the industrial control systems are connected to the Internet. To empower the manufacturing process, ensure the reliability of industrial networks, and reduce downtime and service disruption, the organization decided to install an OT security tool that further protects against security incidents such as cyber espionage, zero-day attacks, and malware.
Which of the following tools must the organization employ to protect its critical infrastructure?
A. Robotium
B. BalenaCloud
C. Flowmon Most Voted
D. IntentFuzzer
## Ans - B (Balena Cloud)
A. Robotium -- Android
B. BalenaCloud -- Clouid provider
C. Flowmon -- rather that, OT thing
D. IntentFuzzer -- Android
# IDS Evasion
## Obfuscating
- Obfuscating is an IDS evasion technique used by attackers who encode the attack packet payload in such a way that the destination host can decode the packet but not the IDS. Encode attack patterns in unicode to bypass IDS filters, but be understood by an IIS web server. (P.1548/1532)
## DNS Tunneling
#### Bypassing Firewalls through the DNS Tunneling Method
- DNS operates using UDP, and it has a 255-byte limit on outbound queries. Moreover, it allows only alphanumeric characters and hyphens. Such small size constraints on external queries allow DNS to be used as an ideal choice to perform data exfiltration by various malicious entities. Since corrupt or malicious data can be secretly embedded into the DNS protocol packets, even DNSSEC cannot detect the abnormality in DNS tunneling. It is effectively used by malware to bypass the firewall to maintain communication between the victim machine and the C&C server. Tools such as NSTX (https://sourceforge.net), Heyoka (http://heyoka.sourceforge.netuse), and Iodine (https://code.kryo.se) use this technique of tunneling traffic across DNS port 53.
CEH v11 Module 12 Page 994
- Bypassing Firewalls through the DNS Tunneling Method
Tools:NSTX, Heyoka, and Iodine use this technique of tunneling traffic across DNS port 53. (P.1586/1570)
# Packet Fragmentation
- SYN/FIN Scanning Using IP Fragments The TCP header is split into several packets so that the packet filters are not able to detect what the packets are intended to do. (P.354/338)#
## DNSSEC Zone walking
#### To distinguish fro zone walking:
- Domain Name System Security Extensions (DNSSEC) zone walking is a type of DNS enumeration technique in which an attacker attempts to obtain internal records if the DNS zone is not properly configured. The enumerated zone information can assist the attacker in building a host network map. Organizations use DNSSEC to add security features to the DNS data and provide protection against known threats to the DNS. This security feature uses digital signatures based on public-key cryptography to strengthen authentication in DNS. These digital signatures are stored in the DNS name servers along with common records such as MX, A, AAAA, and CNAME. While
# Case Variations
By default, in most database servers, SQL is case insensitive.Owing to the case-insensitive option of regular expression signatures in the filters, attackers can mix upper and lower case letters in an attack vector to bypass the detection mechanism.
```
the attacker can easily bypass the filter using the following query:UnIoN sEleCt UsEr_iD, PaSSwOrd fROm aDmiN wHeRe UseR_NamE=’AdMIn’-- (P.2151/2135)
```
# Type of Rootkits
## Kernel-Level Rootkit
- Add malicious code or replaces the original OS kernel and device driver codes.They are difficult to detect and can intercept or subvert the operation of an OS. (P.752/736)
- Kernel rootkits are installed in RING ZERO, prior to AntiMalware software being installed in RING 3. RING 3 apps can't inspect RING 0 due to lack of the appropriate privilege's for RING 3.
# Jim, a professional hacker, targeted an organization that is operating critical industrial infrastructure. Jim used Nmap to scan open ports and running services on systems connected to the organization's OT network. He used an Nmap command to identify Ethernet/IP devices connected to the Internet and further gathered information such as the vendor name, product code and name, device name, and IP address.
Which of the following Nmap commands helped Jim retrieve the required information?
A. nmap -Pn -sT --scan-delay 1s --max-parallelism 1 -p < Port List > < Target IP >
B. nmap -Pn -sU -p 44818 --script enip-info < Target IP > Most Voted
C. nmap -Pn -sT -p 46824 < Target IP >
D. nmap -Pn -sT -p 102 --script s7-info < Target IP >
## Ans -B
- Enumerating Ethernet/IP devices
Ethernet/IP is a very popular protocol used in industrial systems that uses Ethernet as the transport layer and CIP for providing services and profiles needed for the applications. Ethernet/IP devices by several vendors usually operate on UDP port 44818 and we can gather information such as vendor name, product name, serial number, device type, product code, internal IP address, and version.
- enip-info: This NSE script is used to send a EtherNet/IP packet to a remote device that has TCP 44818 open. The script will send a Request Identity Packet and once a response is received, it validates that it was a proper response to the command that was sent, and then will parse out the data. Information that is parsed includes Device Type, Vendor ID, Product name, Serial Number, Product code, Revision Number, status, state, as well as the Device IP.
so it scans that ports auto.
# Ciphers - Triple Data Encryption Standard (3DES)
- Essentially, it performs DES three times with three different keys. 3DES uses a “key bundle” that comprises three DES keys, K1, K2, and K3. Each key is a standard 56-bit DES key.
# Gerard, a disgruntled ex-employee of Sunglass IT Solutions, targets this organization to perform sophisticated attacks and bring down its reputation in the market.
To launch the attacks process, he performed DNS footprinting to gather information about DNS servers and to identify the hosts connected in the target network.
He used an automated tool that can retrieve information about DNS zone data including DNS domain names, computer names, IP addresses, DNS records, and network Whois records. He further exploited this information to launch other sophisticated attacks.
What is the tool employed by Gerard in the above scenario?
A. Towelroot
B. Knative
C. zANTI
D. Bluto (Correct Answer)
- DNS FootprintingExtracting DNS Information
DNS Footprinting - Extracting DNS Information
DNS lookup tools such as DNSdumpster.com, Bluto, and Domain Dossier to retrieve DNS records for a specified domain or hostname. These tools retrieve information such as domains and IP addresses, domain Whois records, DNS records, and network Whois records. (P.220/204)
- Bluto...
"Attackers also use DNS lookup tools such as DNSdumpster.com, Bluto, and Domain Dossier to retrieve DNS records for a specified domain or hostname. These tools retrieve information such as domains and IP addresses, domain Whois records, DNS records, and network Whois records." CEH Module 02 Page 138
# Steven connected his iPhone to a public computer that had been infected by Clark, an attacker. After establishing the connection with the public computer, Steven enabled iTunes Wi-Fi sync on the computer so that the device could continue communication with that computer even after being physically disconnected. Now,
Clark gains access to Steven's iPhone through the infected computer and is able to monitor and read all of Steven's activity on the iPhone, even after the device is out of the communication zone.
Which of the following attacks is performed by Clark in the above scenario?
A. Man-in-the-disk attack
B. iOS jailbreaking
C. iOS trustjacking (Correct Answer)
D. Exploiting SS7 vulnerability
- "iOS Trustjacking is a vulnerability that can be exploited by an attacker to read messages and emails and capture sensitive information such as passwords and banking credentials from a remote location without a victim’s knowledge. This vulnerability exploits the “iTunes Wi-Fi Sync” feature whereby a victim connects his/her phone to any trusted computer (could be of a friend or any trusted entity) that is already infected by the attacker."
CEH Module 17 Page 1521
- https://borwell.com/2018/09/06/ios-trustjacking/
# Five Tier Container Technology
- Tier-1: Developer machines - image creation, testing and accreditation
- Tier-2: Testing and accreditation systems - verification and validation of image contents, signing images and sending them to the registries.
- Tier-3: Registries - storing images and disseminating images to the orchestrators based on requests.
- Tier-4: Orchestrators - transforming images into containers and deploying containers to hosts.
- Tier-5: Hosts - operating and managing containers as instructed by the orchestrator.
# Abel, a cloud architect, uses container technology to deploy applications/software including all its dependencies, such as libraries and configuration files, binaries, and other resources that run independently from other processes in the cloud environment. For the containerization of applications, he follows the five-tier container technology architecture. Currently, Abel is verifying and validating image contents, signing images, and sending them to the registries.
Which of the following tiers of the container technology architecture is Abel currently working in?
A. Tier-1: Developer machines
B. Tier-2: Testing and accreditation systems Most Voted ?????
C. Tier-3: Registries ?????
D. Tier-4: Orchestrators
**Most answer B is correct but examtopic show C is correct and I think B is correct**
# Monitoring Website Traffic of Target Company
- Attackers can monitor a target company’s website traffic using tools such as Web-Stat, Alexa, and Monitis to collect valuable information.
- `Live visitors map`: Tools such as Web-Stat track the geographical location of the users visiting the company’s website. (P.206/190)
# Wireless Network Assessment
- Wireless network assessment determines the vulnerabilities in an organization’s wireless networks. In the past, wireless networks used weak and defective data encryption mechanisms. Now, wireless network standards have evolved, but many networks still use weak and outdated security mechanisms and are open to attack. Wireless network assessments try to attack wireless authentication mechanisms and gain unauthorized access. This type of assessment tests wireless networks and identifies rogue networks that may exist within an organization’s perimeter. These assessments audit client-specified sites with a wireless network. They sniff wireless network traffic and try to crack encryption keys. Auditors test other network access if they gain access to the wireless network.
# Joe works as an IT administrator in an organization and has recently set up a cloud computing service for the organization. To implement this service, he reached out to a telecom company for providing Internet connectivity and transport services between the organization and the cloud service provider.
In the NIST cloud deployment reference architecture, under which category does the telecom company fall in the above scenario?
A. Cloud consumer
B. Cloud broker
C. Cloud auditor
D. Cloud carrier (Correct Answer)
- NIST Cloud Deployment Reference Architecture
Cloud Carrier - An intermediary for providing connectivity and transport services between cloud consumers and providers. (P.2823/2807)
# Agent Smith Attacks
- Agent Smith attacks are carried out by luring victims into downloading and installing malicious
apps designed and published by attackers in the form of games, photo editors, or other attractive tools from third-party app stores such as 9Apps. Once the user has installed the app, the core malicious code inside the application infects or replaces the legitimate apps in the victim’s mobile device C&C commands. The deceptive application replaces legitimate apps such as WhatsApp, SHAREit, and MX Player with similar infected versions. The application sometimes also appears to be an authentic Google product such as Google Updater or Themes. The attacker then produces a massive volume of irrelevant and fraudulent advertisements on the victim’s device through the infected app for financial gain. Attackers exploit these apps to steal critical information such as personal information, credentials, and bank details, from the victim’s mobile device through C&C commands
# This form of encryption algorithm is a symmetric key block cipher that is characterized by a 128-bit block size, and its key size can be up to 256 bits. Which among the following is this encryption algorithm?
A. HMAC encryption algorithm
B. Twofish encryption algorithm (Correct Answer)
C. IDEA
D. Blowfish encryption algorithm
- Blowfish has bigger size then 256bit, idea has just 64bit. HMAC is for hashing not encytpting
- Twofish uses a block size of 128 bits and key sizes up to 256 bits. It is a Feistel cipher.encryption speed.
- 256 synonymous to two fish, na my own way be that, blowfish is from 32 to 248 bit, it really blow
# Ethical hacker Jane Smith is attempting to perform an SQL injection attack. She wants to test the response time of a true or false response and wants to use a second command to determine whether the database will return true or false results for user IDs.
Which two SQL injection types would give her the results she is looking for?
A. Out of band and boolean-based
B. Union-based and error-based (True Answer)
C. Time-based and union-based
D. Time-based and boolean-based Most Voted
- Union based SQL injection allows an attacker to extract information from the database by extending the results returned by the first query. The Union operator can only be used if the original/new queries have an equivalent structure Error-based SQL injection is an In-band injection technique where the error output from the SQL database is employed to control the info inside the database. In In-band injection, the attacker uses an equivalent channel for both attacks and collect data from the database.
- Not sure about D. Yes, it fits, could perfetcly be but...
"... wants to use a second command..." points directly to a UNION query. And yes, you can craft a UNION query to send a time- based request and a True/ false one too...
# Slowloris Attack
- Slowloris is a DDoS attack tool used to perform layer-7 DDoS attacks to take down web infrastructure. It is distinctly different from other tools in that it uses perfectly legitimate HTTP traffic to take down a target server. In Slowloris attacks, the attacker sends partial HTTP requests to the target web server or application. Upon receiving the partial requests, the target server opens multiple connections and waits for the requests to complete. However, these requests remain incomplete, causing the target server’s maximum concurrent connection pool to be filled up and additional connection attempts to be denied.
CEHv11 page 1322
- The following are examples for application layer attack techniques:
*Hypertext Transfer Protocol (HTTP) flood attack
*Slowloris attack
*UDP application layer flood attack
# ession fixation attack
Session Fixation is an attack that allows an attacker to hijack a sound user session. The attack explores a limitation within the means the net application manages the session ID, a lot of specifically the vulnerable web application. once authenticating a user, it doesn’t assign a new session ID, creating it possible to use an existent session ID. The attack consists of getting a valid session ID (e.g. by connecting to the application), inducing a user to authenticate himself with that session ID, then hijacking the user-validated session by the data of the used session ID. The attacker has got to give a legitimate internet application session ID and try to make the victim’s browser use it.
# Gilbert, a web developer, uses a centralized web API to reduce complexity and increase the integrity of updating and changing data. For this purpose, he uses a web service that uses HTTP methods such as PUT, POST, GET, and DELETE and can improve the overall performance, visibility, scalability, reliability, and portability of an application.
What is the type of web-service API mentioned in the above scenario?
A. RESTful API (correct answer)
B. JSON-RPC
C. SOAP API
D. REST API
- RESTful API: RESTful API is a RESTful service that is designed using REST principles and HTTP communication protocols. RESTful is a collection of resources that use HTTP methods such as PUT, POST, GET, and DELETE. RESTful API is also designed to make applications independent to improve the overall performance, visibility, scalability, reliability, and portability of an application. APIs with the following features can be referred to as to RESTful APIs: o Stateless: The client end stores the state of the session; the server is restricted to save data during the request processing
o Cacheable: The client should save responses (representations) in the cache. This feature can enhance API performance
pg. 1920 CEHv11 manual.
- Web Services APIs - RESTful API
also known as RESTful services, are designed using REST principles and HTTP communication protocols. RESTful is a collection of resources that use HTTP methods such as PUT, POST, GET, and DELETE.RESTful API is also designed to make applications independent to improve the overall performance, visibility, scalability, reliability, and portability of an application. (P.1920/1904)
# Blind Hijacking Attack
- acker may use techniques such as session prediction or IP spoofing. Session prediction involves `guessing the session ID` or other information used to identify the session, while IP spoofing involves forging the IP address of one of the machines in the session in order to gain access to the communication channel.
- attacker guessing the next sequence. If the attacker was `not predicting` the next sequence it would `TCP/IP Hijacking`.
- TCP/IP hijacking involves using spoofed packets to seize control of a connection between a victim and target machine.
# Port Scanning
- ACK -> no response = filtered
- ACK -> RST/ACK = unfiltered
# If you send a TCP ACK segment to a known closed port on a firewall but it does not respond with an RST, what do you know about the firewall you are scanning?
A. It is a non-stateful firewall.
B. There is no firewall in place.
C. It is a stateful firewall.
D. This event does not tell you anything about the firewall. (`Correct Answer`)
- I'm also going with D and this is why:
The question says that you are knocking on a known closed port on the Firewall. This is important.
If you know beforehand the port is closed on the firewall itself, you won't get any response regardless if it's a stateless or statefull firewall.
- What most people are saying about detecting stateful firewalls is with regards to an open port on the firewall... If the port is open on the firewall and you try to inject an ACK packet, a stateful firewall will understand that's an unsolicited packet and discard it, so you get no response from the server itself
# AndroidManifest.xml
- which consists of essential information about the APK file.
- Note: The manifest file contains important information about the app that is used by development tools, the Android system, and app stores. It contains the app’s package name, version information, declarations of app components, requested permissions, and other important data. It is serialized into a binary XML format and bundled inside the app’s APK file.
- A. AndroidManifest.xml - Every app project must have an AndroidManifest.xml file (with precisely that name) at the root of the project source set. The manifest file describes essential information about your app to the Android build tools, the Android operating system, and Google Play.
- Among many other things, the manifest file is required to declare the following:
- The app's package name, which usually matches your code's namespace. The Android build tools use this to determine the location of code entities when building your project. When packaging the app, the build tools replace this value with the application ID from the Gradle build files, which is used as the unique app identifier on the system and on Google Play. Read more about the package name and app ID.
The components of the app, which include all activities, services, broadcast receivers, and content providers. Each component must define basic properties such as the name of its Kotlin or Java class. It can also declare capabilities such as which device configurations it can handle, and intent filters that describe how the component can be started. Read more about app components ...
# DNS Cache Poisoning
- DNS cache poisoning attack, but the first step would always be the same: the attacker must send queries to the DNS server to learn about the name resolution process and cache records. Then, the attacker can exploit the weaknesses found to poison the DNS cache and redirect traffic to malicious sites.
- DNS CACHE Poisoning refers to altering or adding forged DNS records in the DNS resolver cache so that a DNS query is redirected to a malicious site.
However, the question is asking the FIRST STEP for a hacker. The forged and altered DNS records are the end result.
The FIRST STEP is the attacker Queries for DNS info.
(P.1165/1181)
- I dont understand how people can not see the answers from their reference. Guys look at the diagram carefully 1st step you will see very clearly- " Query for DNS info" 1st step.
Subject is closed. Dont waste your time.
# Password Salting
Password salting is a technique where a random string of characters are added to the password before calculating their hashes.Advantage: Salting makes it more difficult to reverse the hashes and defeat pre-computed hash attacks.
#Note: Windows password hashes are not salted. (P.616/600)
# Whois Footprinting
which helps in gathering domain information such as information regarding the owner of an organization, its registrar, registration details, its name server, and contact information.
Regional Internet Registries (RIRs) maintain Whois databases, which contain the personal information of domain owners.
- Using this information, an attacker can create a map of the organization's network, mislead domain owners with social engineering, and then obtain internal details of the network. RIRs includ: ARIN (American Registry for Internet Numbers). (P.214/198)
- `https://search.arin.net/rdap/?query=199.43.0.43
`
# WPA3 - Enterprise
- It protects sensitive data using many cryptographic algorithms
It provides authenticated encryption using GCMP-256
It uses HMAC-SHA-384 to generate cryptographic keys It uses ECDSA-384 for exchanging keys
# Web Server Attacks - DNS Server Hijacking
- Attacker compromises the DNS server and changes the DNS settings so that all the requests coming towards the target web server are redirected to his/her own malicious server. (P.1623/1607)
# Web Server Attacks - Web Server Misconfiguration
Server misconfiguration refers to configuration weaknesses in web infrastructure that can be exploited to launch various attacks on web servers such as directory traversal, server intrusion, and data theft.
- `php.ini file` - This configuration generates verbose error messages.
-
# Web Server Attacks - DHCP Starvation Attack
- This is a denial-of-service (DoS) attack on the DHCP servers where the attacker broadcasts forged DHCP requests and tries to lease all the DHCP addresses available in the DHCP scope
Therefore, the legitimate user is unable to obtain or renew an IP address requested via DHCP, and fails to get access to the network
- In a DHCP starvation attack, an attacker floods the DHCP server by sending numerous DHCP requests and uses all of the available IP addresses that the DHCP server can issue. As a result, the server cannot issue any more IP addresses, leading to a DoS attack. Because of this issue, valid users cannot obtain or renew their IP addresses; thus, they fail to access their network. An attacker broadcasts DHCP requests with spoofed MAC addresses with the help of tools such as Yersinia, Hyenae, and Gobbler.
# How to Identify Target System OS
- Attackers can identify the OS running on the target machine by looking at the Time To Live (TTL) and TCP window size in the IP header of the first packet in a TCP session.Sniff/capture the response generated from the target machine using packet-sniffing tools like Wireshark and observe the TTL and TCP window size fields.
#Time to Live (TTL) 128 is Windows / TTL 64 is Linux (P.341/325)
# Types of hardware encryption devices - Trusted platform module (TPM)
- TPM is a crypto-processor or a chip that is present in the motherboard. It can securely store the encryption keys and perform many cryptographic operations. TPM offers various features such as authenticating platform integrity, providing full disk encryption capabilities, performing password storage, and providing software license protection. (P.3058/3042)
# Management Information Base (MIB)
- DHCP.MIB: Monitors network traffic between DHCP servers and remote hosts
- HOSTMIB.MIB: Monitors and manages host resources
- LNMIB2.MIB: Contains object types for workstation and server services
- MIB_II.MIB: Manages TCP/IP-based Internet using a simple architecture and system
- WINS.MIB: For the Windows Internet Name Service (WINS)
# Bluetooth Hacking
- (A) `BlueSmacking` is a technique to performe a `Denial of Service attack` into Bluetooth devices abuzing the L2PCAP layer.
- (B) `Bluejacking` is the sending of `unsolicited messages over Bluetooth` to Bluetooth-enabled devices
- Bluejacking is the use of Bluetooth to send messages to users without the recipient's consent, similar to email spamming. Prior to any Bluetooth communication, the device initiating the connection must provide a name that is displayed on the recipient's screen. Sending anonymous messages over Bluetooth to Bluetooth-enabled devices, via the OBEX(Object Exchange) protocol. (P.2344/2328)
- (C) `Bluesnarfing` is an attack to `access information from wireless devices that transmit using the Bluetooth protocol`.
- (D) `Bluebugging` is a hacking technique that `allows individuals to access a device with a discoverable Bluetooth connection.`
# aLTEr attack
- aLTEr attacks are usually performed on LTE devices
- Attacker installs a virtual (fake) communication tower between two authentic endpoints intending to mislead the victim
- This virtual tower is used to interrupt the data transmission between the user and real tower attempting to hijack the active session.
# Incident Handling and Response
1. Preparation
2. Incident Recording and Assignment
3. Incident Triage
4. Notification
5. Containment
6. Evidence Gathering and Forensic Analysis
# Clark is a professional hacker. He created and configured multiple domains pointing to the same host to switch quickly between the domains and avoid detection.
Identify the behavior of the adversary in the above scenario.
A. Unspecified proxy activities (Correct Answer)
B. Use of command-line interface
C. Data staging
D. Use of DNS tunneling
- `Unspecified Proxy Activities` An adversary can create and configure multiple domains pointing to the same host, thus, allowing an adversary to switch quickly between the domains to avoid detection. Security professionals can find unspecified domains by checking the data feeds that are generated by those domains. Using this data feed, the security professionals can also find any malicious files downloaded and the unsolicited communication with the outside network based on the domains
- Adversary Behavioral Identification
Adversary behavioral identification involves the identification of the common methods or techniques followed by an adversary to launch attacks on or to penetrate an organization’s network.It gives the security professionals insight into upcoming threats and exploits.
3.Unspecified Proxy Activities - An adversary can create and configure multiple domains pointing to the same host, thus, allowing an adversary to switch quickly between the domains to avoid detection. (P.38/22)
# SE Techniques
# Pharming
- Pharming is a social engineering technique in which the attacker executes malicious programs on a victim’s computer or server, and when the victim enters any URL or domain name, it automatically redirects the victim’s traffic to an attacker-controlled website. This attack is also known as “Phishing without a Lure.” The attacker steals confidential information like credentials, banking details, and other information related to web-based services.
# Skimming
- refers to stealing credit or debit card numbers by using special storage devices called skimmers or wedges when processing the card.
# Pretexting
- Fraudsters may impersonate executives from financial institutions, telephone companies, and other businesses. They rely on “smooth-talking” and win the trust of an individual to reveal sensitive information.
# Dragonblood Vulnerability on wireless network
is a set of vulnerabilities in the `WPA3 security standard that allows attackers to recover keys, downgrade security mechanisms, and launch various information-theft attacks`
- Attackers can use various tools, such as `Dragonslayer`, `Dragonforce`, `Dragondrain`, and `Dragontime`, to exploit these vulnerabilities and launch attacks on WPA3-enabled networks.
- The design flaws we discovered can be divided in two categories. `The first category` consists of downgrade attacks against WPA3-capable devices, and `the second category` consists of weaknesses in the Dragonfly handshake of WPA3, which in the Wi-Fi standard is better known as the Simultaneous Authentication of Equals (SAE) handshake.
- The discovered flaws can be abused to recover the password of the Wi-Fi network, launch resource consumption attacks, and force devices into using weaker security groups. All attacks are against home networks (i.e. WPA3-Personal), where one password is shared among all users.
# Advanced Persistent Threats (APTs)
- Advanced persistent threats (APTs) are defined as a type of network attack, where an attacker gains unauthorized access to a target network and remains `undetected for a long period` of time.Attacks is to obtain sensitive information rather than sabotaging the organization and its network. (P.865/849)
- he word “persistent” signifies the external command-and-control (C&C) system that continuously extracts the data and monitors the victim’s network. The word “threat” signifies human involvement in coordination. APT attacks are highly sophisticated attacks whereby an attacker uses well-crafted malicious code along with a combination of multiple zero-day exploits to gain access to the target network.
# DLE/IPID header scan
- Every IP packet on the Internet has a fragment identification number (IPID); an OS increases the IPID for each packet sent, thus, probing an IPID gives an attacker the number of packets sent after the last probe.
- IPID increased by 2 will indicate an open port , 1 will indicate a closed port.
- `Nmap -sI <Zombie IP address> <target IP address> (P.315/299`
# Jailbreak
- Untethered jailbreak, a type of iOS jailbreak that allows a device to boot up jailbroken every time it is rebooted. This does NOT require a “re-jailbreaking” process. The only way to get rid of a jailbreak using this process is to restore the device.
- he invalid options are (for reference):
Semi-tethered Jailbreaking: A semi-tethered jailbreak has the property that if the user turns the device off and back on, the device will completely start up and will no longer have a patched kernel, but it will still be usable for normal functions. To use jailbroken addons, the user need to start the device with the help of a jailbreaking tool
- Tethered Jailbreaking: With a tethered jailbreak, if the device starts back up on its own, it will no longer have a patched kernel, and it may get stuck in a partially started state; for it to completely start up with a patched kernel, it must be "re-jailbroken" with a computer (using the "boot tethered" feature of a jailbreaking tool) each time it is turned on
- Semi-untethered Jailbreaking A semi-untethered jailbreak is similar to a semi-tethered jailbreak. In this type of a jailbreak, when the device reboots, the kernel is not patched, but the kernel can still be patched without using a computer. This is done using an app installed on the device
- In a tethered jailbreak, the jailbreak software modifies the kernel of the iOS device to remove software restrictions and allow for the installation of third-party applications. However, this modification is not permanent and is lost when the device is rebooted.
- To maintain the jailbreak, the user must connect the device to a computer and run the jailbreak software again. The software patches the kernel during the boot process, allowing the device to become jailbroken once again.
- Tethered jailbreaking is generally considered less desirable than untethered jailbreaking, as it requires the user to connect the device to a computer each time it is rebooted. Untethered jailbreaking, on the other hand, does not require the user to connect the device to a computer to maintain the jailbreak.
- It's important to note that jailbreaking an iOS device can potentially expose the device to security risks and can void its warranty. Users should carefully consider the risks and benefits before deciding to jailbreak their iOS device.
# Webhooks
- are user-defined HTTP callback or push APIs that are raised based on events
triggered, such as comment received on a post and pushing code to the registry. A webhook allows an application to update other applications with the latest information. Once invoked, it supplies data to the other applications, which means that users instantly receive real-time information. Webhooks are sometimes called “Reverse APIs” as they provide what is required for API specification, and the developer should create an API to use a webhook.
- What are Webhooks? Webhooks are user-defined HTTP callback or push APIs that are raised based on events triggered, such as comment received on a post and pushing code to the registry. A webhook allows an application to update other applications with the latest information. Once invoked, it supplies data to the other applications, which means that users instantly receive real-time information. Webhooks are sometimes called “Reverse APIs” as they provide what is required for API specification, and the developer should create an API to use a webhook. A webhook is an API concept that is also used to send text messages and notifications to mobile numbers or email addresses from an application when a specific event is triggered. For instance, if you search for something in the online store and the required item is out of stock, you click on the “Notify me” bar to get an alert from the application when that item is available for purchase. These notifications from the applications are usually sent through webhooks.
Operation of Webhooks
# HIPAA(health insurance portability and accountability act)
- The HIPAA Privacy Rule provides federal protections for the individually identifiable health information held by covered entities and their business associates and gives patients an array of rights to that information. The Security Rule specifies a series of administrative, physical, and technical safeguards for covered entities and their business associates to use to ensure the confidentiality, integrity, and availability of electronically protected health information. (P.96/80)
- HIPAA(Health Insurance Portability and Accountability Act)/PHI (Protected Health Information)
# Sarbanes Oxley Act(SOX)
- Enacted in 2002, the Sarbanes-Oxley Act is designed to protect investors and the public by increasing the accuracy and reliability of corporate disclosures
# NetBIOS Suffixes
- NetBIOS name is a unique 16 character used to identify the network devices over TCP/IP.
00: Workstation Service (workstation name)
03: Windows Messenger service.
06: Remote Access Service.
20: File Service (also called Host Record)
21: Remote Access Service client.
1B: Domain Master Browser – Primary Domain Controller for a domain.
1D: Master Browser.
# STP Attack
In a Spanning Tree Protocol (STP) attack, attackers connect a rogue switch into the network to change the operation of the STP protocol and sniff all the network traffic.
- STP is used in LAN-switched networks with the primary function of removing potential loops within the network. STP ensures that the traffic inside the network follows an optimized path to enhance network performance.
- In this process, a switch inside the network is appointed as the root bridge. After the selection of the root bridge, other switches in the network connect to it by selecting a root port (the closest port to the root bridge). The root bridge is selected with the help of Bridge Protocol Data Units (BPDUs). BPDUs each have an identification number known as a BID or ID. These BIDs consist of the Bridge Priority and the MAC address.
- By default, the value of the Bridge Priority is 32769. If an attacker has access to two switches, he/she introduces a rogue switch in the network with a priority lower than any other switch in the network. This makes the rogue switch the root bridge, thus allowing the attacker to sniff all the traffic flowing in the network.
- Attackers connect a rogue switch into the network to change the operations of the STP protocol and sniff all the network traffic.Attackers configure the rogue switch such that its priority is less than that of any other switch in the network, which makes it the root bridge, thus allowing the attackers to sniff all the traffic flowing in the network. (P.1167/1151)
# which of the following protocols can be used to secure an LDAP service against anonymous queries?
A. SSO
B. RADIUS
C. WPA
D. NTLM
## Answer: D
- CEH v11 page 493 (Use NTLM or any basic authentication mechanism to limit access to legitimate users only)
SMB
- LDAP Enumeration Countermeasures:By default, LDAP traffic is transmitted unsecured (Port 389); therefore, use Secure Sockets Layer (SSL) or STARTTLS technology to encrypt the traffic (Port 636). Use NTLM or any basic authentication mechanism to limit access to legitimate users. (P.494/478)
- Explanation: In a Windows network, nongovernmental organization ``(New Technology) local area network Manager (NTLM)`` could be a suite of Microsoft security protocolssupposed to produce authentication, integrity, and confidentiality to users.
- NTLM is that the successor to the authentication protocol in Microsoft local area networkManager (LANMAN), Associate in Nursing older Microsoft product. The NTLM protocol suite is enforced in an exceedingly Security Support supplier, which mixesthe local area network Manager authentication protocol, NTLMv1, NTLMv2 and NTLM2 Session protocols in an exceedingly single package. whether or not theseprotocols area unit used or will be used on a system is ruled by cluster Policy settings, that totally different|completely different} versions of Windows have differentdefault settings.
- NTLM passwords area unit thought-about weak as a result of they will be brute-forced very simply with fashionable hardware.NTLM could be a challenge-response authentication protocol that uses 3 messages to authenticate a consumer in an exceedingly affiliation orientating setting(connectionless is similar), and a fourth extra message if integrity is desired.First, the consumer establishes a network path to the server and sends a NEGOTIATE_MESSAGE advertising its capabilities.Next, the server responds with CHALLENGE_MESSAGE that is employed to determine the identity of the consumer.
- Finally, the consumer responds to thechallenge with Associate in Nursing AUTHENTICATE_MESSAGE.The NTLM protocol uses one or each of 2 hashed word values, each of that are keep on the server (or domain controller), and that through a scarcity of seasoningarea unit word equivalent, that means that if you grab the hash price from the server, you’ll evidence while not knowing the particular word. the 2 area unit the lmHash (a DES-based operate applied to the primary fourteen chars of the word born-again to the standard eight bit laptop charset for the language), and also the ntHash (MD4 of the insufficient endian UTF-16 Unicode password). each hash values area unit sixteen bytes (128 bits) every.The NTLM protocol additionally uses one among 2 a method functions, looking on the NTLM version.National Trust LanMan and NTLM version one use the DES primarily based LanMan a method operate (LMOWF), whereas National TrustLMv2 uses the NT MD4primarily based a method operate (NTOWF)
# Replay Attack
- Types of SDR-based attacks performed by attackers to break into an IoT environment:
- Replay Attack This is the major attack described in IoT threats, in which attackers can capture the command sequence from connected devices and use it for later retransmission. An attacker can perform the below steps to launch a replay attack: o Attacker targets the specified frequency that is required to share information between devices
- After obtaining the frequency, the attacker can capture the original data when the commands are initiated by the connected devices
- Once the original data is collected, the attacker uses free tools such as URH (Universal Radio Hacker) to segregate the command sequence
- Attacker then injects the segregated command sequence on the same frequency into the IoT network, which replays the commands or captured signals of the devices
# Wired Equivalent Privacy (WEP) Encryption
WEP is a security protocol defined by the 802.11b standard; it was designed to provide a wireless LAN with a level of security and privacy comparable to that of a wired LAN.It has significant vulnerabilities and design flaws and can therefore be easily cracked. (P.2199/2183)
# Zig-Bee:
- This is another short-range communication protocol based on the IEEE 203.15.4 standard. Zig-Bee is used in devices that transfer data infrequently at a low rate in a restricted area and within a range of 10–100 m.
- he 802.15.4 standard has a low data rate and complexity. The specification used in this standard is ZigBee, which transmits long-distance data through a mesh network. The specification handles applications with a low data rate of 250 Kbps, but its use increases battery life.
- 802.15.4 for Zigbee , bluetooth is 802.15.1
- The operating range of `LPWAN` technology varies from `a few kilometers in urban` areas to` over 10 km in rural` settings
# AirPcap ???
- was a specialized solution to do what you can do on Linux (injection/monitor mode). as far as I know you cannot on WINDOWS capture Wifi traffic without the outdated Aircap. Winpcap does not put the Wifi card into monitor mode on windows.
- apture is mostly limited by Winpcap and not by Wireshark. However, Wireshark includes Airpcap support, a special -and costly- set of WiFi hardware that supports WiFi traffic monitoring in monitor mode. In other words, it allows capturing WiFi network traffic in promiscuous mode on a WiFi network. However these cards have been discontinued and are deprecated, so they cannot capture traffic on networks running the latest WiFi standards (802.11ac)
- The AirPcap adapters from Riverbed Technology allow full raw 802.11 captures under Windows, including radiotap information. Note that the AirPcap adaptors are no longer being sold by Riverbed, as announced in their End-of-Availability (EOA) Notice on October 2, 2017.
# Tailgating Vs Piggybacking
- Tailgating" implies no consent (similar to a car tailgating another vehicle on a road), while "piggybacking" usually implies consent of the authorized person
- Piggybacking - An authorized person intentionally or unintentionally allows an unauthorized person to pass through a secure door e.g., “I forgot my ID badge at home. Please help me”.
- Tailgating - The attacker, wearing a fake ID badge, enters a secured area by closely following an authorized person through a door that requires key access.
# Wireless Security Tools - Wi-Fi IPSs
- Wi-Fi IPSs block wireless threats by automatically scanning, detecting, and classifying unauthorized wireless access and rogue traffic to the network, thereby preventing neighboring users or skilled hackers from gaining unauthorized access to the Wi-Fi networking resources. (P.2374/2358)
- wireless intrusion prevention system (WIPS) is a network device that monitors the radio spectrum to detect APs (intrusion detection) without the host’s permission in nearby locations. It can also implement countermeasures automatically. WIPSs protect networks against wireless threats and provide administrators the ability to detect and prevent various network attacks.
EC-Council C|EH v11 Courseware, page 2369
# You are tasked to configure the DHCP server to lease the last 100 usable IP addresses in subnet 10.1.4.0/23.
Which of the following IP addresses could be leased as a result of the new configuration?
A. 10.1.255.200
B. 10.1.4.156
C. 10.1.4.254
D. 10.1.5.200
- To answer this question, you need to find the range of addresses in the subnet, which typically then means you need to calculate the subnet ID and subnet broadcast address. With a subnet ID/mask of 10.1.4.0/23, the mask converts to 255.255.254.0.
- To find the subnet broadcast address, following the decimal process described in this chapter, you can copy the subnet ID’s first two octets because the mask’s value is 255 in each octet. You write a 255 in the fourth octet because the mask has a 0 on the fourth octet. In octet 3, the interesting octet, add the magic number (2) to the subnet ID’s value (4), minus 1, for a value of 2 + 4 – 1 = 5. (The magic number in this case is calculated as 256 – 254 = 2.) That makes the broadcast address 10.1.5.255. The last usable address is 1 less: 10.1.5.254. The range that includes the last 100 addresses is 10.1.5.155 – 10.1.5.254.
- 10.1.4.0/23 = 10.1.4.0 255.255.254.0
- Range is 10.1.4.0 - 10.1.5.255
- 10.1.4.0 = network address
- 10.1.5.255 = broadcast address

# Hping2 Scan Mode
Mode
default mode TCP
- 0 --rawip RAW IP mode
- 1 --icmp ICMP mode
- 2 --udp UDP mode
- 8 --scan SCAN mode.
Example: `hping --scan 1-30,70-90 -S www.target.host`
- 9 --listen listen mode
- Hping performs an ICMP ping scan by specifying the argument -1 in the command line. You may use --ICMP or -1 as the argument in the command line. By issuing the above command, hping sends an ICMP echo request to x.x.x.x and receives an ICMP reply similar to a ping utility.
# AAA Protocol
- The Diameter protocol is also an AAA protocol like RADIUS and TACACS+, but it is designed to overcome some of the limitations of RADIUS, particularly in terms of security and scalability. Diameter is an IETF standard protocol that supports a wide range of authentication, authorization, and accounting (AAA) applications, including network access and mobile IP. It has features such as Transport Layer Security (TLS) encryption, dynamic discovery of servers, and a flexible message structure that allow for greater security and scalability. Therefore, Diameter can also handle the requirement described in the question
- The Diameter protocol is also an AAA protocol like RADIUS and TACACS+, but it is designed to overcome some of the limitations of RADIUS, particularly in terms of security and scalability. Diameter is an IETF standard protocol that supports a wide range of authentication,
- authorization, and accounting (AAA) applications, including network access and mobile IP. It has features such as Transport Layer Security (TLS) encryption, dynamic discovery of servers, and a flexible message structure that allow for greater security and scalability. Therefore, Diameter can also handle the requirement described in the question
- Remote Authentication Dial-In User Service (RADIUS) is an authentication protocol that provides centralized authentication, authorization, and accounting (AAA) for the remote access servers to communicate with the central server
Radius Authentication Steps: 1. The client initiates the connection by sending an Access-Request packet to the server
2. The server receives the access request from the client and compares the credentials with the ones stored in the database. If the provided information matches, then it sends the Accept-Accept message along with the Access-Challenge to the client for additional authentication, otherwise it sends back the Accept-Reject message
# Anomaly Detection
- Anomaly detection, or “not-use detection,” differs from signature recognition. An anomaly is detected when an event occurs outside the tolerance threshold of normal traffic.Therefore, `any deviation from regular use is an attack`. Anomaly detection detects intrusions based on the fixed behavioral characteristics of the users and components in a computer system. (P.1480/1464)
# Snort
- `Intrusion Detection Tools: Snort`
- Snort is an open-source network intrusion detection system, capable of performing real-time traffic analysis and packet logging on IP networks.
- Uses of Snort:1. Straight packet sniffer such as tcpdump2. Packet logger (useful for network traffic debugging, etc.)3. Network intrusion prevention system (P.1518/1502)
# You have compromised a server and successfully gained a root access. You want to pivot and pass traffic undetected over the network and evade any possible
Intrusion Detection System. What is the best approach?
A. Use Alternate Data Streams to hide the outgoing packets from this server.
B. Use HTTP so that all traffic can be routed vis a browser, thus evading the internal Intrusion Detection Systems.
C. Install Cryptcat and encrypt outgoing packets from this server. (Correct Answer)
D. Install and use Telnet to encrypt all outgoing traffic from this server.
- Employ a crypter such as BitCrypter to encrypt the Trojan to evade detection by firewalls/IDS. (P.904/888)
- CryptCat is a simple Unix utility which reads and writes data across network connections, using TCP or UDP protocol while encrypting the data being transmitted.
# Non-repudiation
- assurance that someone cannot deny the validity of something.
# The security administrator of ABC needs to permit Internet traffic in the host 10.0.0.2 and UDP traffic in the host 10.0.0.3. He also needs to permit all FTP traffic to the rest of the network and deny all other traffic. After he applied his ACL configuration in the router, nobody can access the ftp, and the permitted hosts cannot access the Internet. According to the next configuration, what is happening in the network?
A. The ACL 104 needs to be first because is UDP
B. The first ACL is denying all TCP traffic and the other ACLs are being ignored by the router (Correct Answer)
C. The ACL for FTP must be before the ACL 110
D. The ACL 110 needs to be changed to port 80
# Which access control mechanism allows for multiple systems to use a central authentication server (CAS) that permits users to authenticate once and gain access to multiple systems?
A. Role Based Access Control (RBAC)
B. Discretionary Access Control (DAC)
C. Single sign-on (correct Answer)
D. Windows authentication
- Single Sign-on (SSO) authentication processes permit a user to sign into an application using a single set of credentials and use the same login session to access multiple applications irrespective of domains or platforms
- The communication between these applications can be done through SAML messages SAML messages are encrypted using Base64 encoding and can be easily decrypted to extract the content of messages Attackers use tools such as SAML Raider to bypass SAM-based SSO authentication
# Internet Protocol Security (IPsec)
- uses Encapsulation Security Payload (ESP), Authentication Header (AH), and Internet Key Exchange (IKE) to `secure communication between virtual private network (VPN)` end points by authenticating and encrypting each IP packet of a communication session.
- Transport Mode - In the transport mode (also ESP), IPsec encrypts only the payload of the IP packet, leaving the header untouched. It authenticates two connected computers and provides the option of encrypting data transfer. (P.1464/1448)
# Shell Shock Vulnerability (CVE-2014-6271.)
This vulnerability impacts the Bourne Again Shell "Bash". Bash is not usually available through a web application but can be indirectly exposed through a Common Gateway Interface "CGI".
# Firewalk has just completed the second phase (the scanning phase) and a technician receives the output shown below. What conclusions can be drawn based on these scan results?
TCP port 21 no response -
TCP port 22 no response -
TCP port 23 Time-to-live exceeded
A. The lack of response from ports 21 and 22 indicate that those services are not running on the destination server
B. The scan on port 23 was able to make a connection to the destination host prompting the firewall to respond with a TTL error
C. The scan on port 23 passed through the filtering device. This indicates that port 23 was not blocked at the firewall (Correct Answer)
D. The firewall itself is blocking ports 21 through 23 and a service is listening on port 23 of the target host
- The entire route is determined using any of the traceroute techniques available
A packet is sent with the TTL equal to the distance to the target
If the packet times out, it is resent with the TTL equal to the distance to the target minus one.
If an ICMP type 11 code 0 (Time-to-Live exceeded) is received, the packet was forwarded and so the port is not blocked.
- If no response is received, the port is blocked on the gateway.
- Firewall Evasion Techniques
Firewall Identification - Firewalking
a method of collecting information about remote networks behind firewalls. Technique that uses TTL values to determine gateway ACL filters and map networks by analyzing the IP packet response. (P.1567/1551)
`Nmap -O -sA <target IP address>`
# N-tier application architecture
- N-tier architecture would involve dividing an application into three different tiers.
- Presentation tier - To translate tasks and results to something the user can understand
- Logic tier - Coordinates the application, processes commands, makes logical decisions and evaluations, and performs calculations. It also moves and processes data between the two surrounding layers.
- Data tier - Here information is stored and retrieved from a database or file system.
# Phishing Vs Pharming
- Computer-based Social Engineering: Phishing
Pharming is a social engineering technique in which the attacker executes malicious programs on a victim’s computer or server, and when the victim enters any URL or domain name, it automatically redirects the victim’s traffic to an attacker-controlled website.This attack is also known as “Phishing without a Lure.”
- Pharming attack can be performed in two ways: DNS Cache Poisoning and Host File Modification
- Phishing is a technique in which an attacker sends an email or provides a link falsely claiming to be from a legitimate site to acquire a user’s personal or account information. The attacker registers a fake domain name, builds a lookalike website, and then mails the fake website’s link to users. When a user clicks on the email link, it redirects them to the fake webpage, where they are lured into sharing sensitive details such as their address and credit card information. Some of the reasons behind the success of phishing scams include users’ lack of knowledge, being visually deceived, and not paying attention to security indicators.
- The Pharming, also known as domain spoofing, is an advanced form of phishing in which the attacker redirects the connection between the IP address and its target server. The attacker may use cache poisoning (modifying the Internet address to that of a rogue address) to do so. When the users type in the Internet address, it redirects them to a rogue website that resembles the original.
# Virus Detection Methods
1. Scanning: Once a virus is detected, it is possible to write scanning programs that look for signature string characteristics of the virus
2. Integrity Checking: Integrity checking products work by reading the entire disk and recording integrity data that act as a signature for the files and system sectors
3. Interception: The interceptor monitors the operating system requests that are written to the disk
4. Code Emulation: In code emulation techniques, the antivirus executes the malicious code inside a virtual machine to simulate CPU and memory activities These techniques are considered very effective in dealing with encrypted and polymorphic viruses if the virtual machine mimics the real machine
5. Heuristic Analysis: Heuristic analysis can be static or dynamic In static analysis, the antivirus analyses the file format and code structure to determine if the code is viral In dynamic analysis, the antivirus performs a code emulation of the suspicious code to determine if the code is viral
# Packet Sniffer
- Sniffers operate at the data link layer and can capture packets. (P.1105)
- The data link layer is the second layer of the OSI model. In this layer, data packets are encoded and decoded into bits. Sniffers operate at the data link layer and can capture packets from this layer. Networking layers in the OSI model are designed to work independently of each other; thus, if a sniffer sniffs data in the data link layer, the upper OSI layers will not be aware of the sniffing.
# You are a security officer of a company. You had an alert from IDS that indicates that one PC on your Intranet is connected to a blacklisted IP address (C2 Server) on the Internet. The IP address was blacklisted just before the alert. You are starting an investigation to roughly analyze the severity of the situation. Which of the following is appropriate to analyze?
A. IDS log
B. Event logs on domain controller
C. Internet Firewall/Proxy log. (Correct Answer)
D. Event logs on the PC
# Yagi antenna
- also called Yagi-Uda antenna, is a unidirectional antenna commonly used in communications at a frequency band of 10 MHz to VHF and UHF.
# Wrieless Range
802.11a Range 35- 100 meters
802.11b Range 35- 140 meters
802.11g Range 38- 140 meters
802.16 (WiMAX) Range 1- 6 miles
# USB Dumper
- is an simple yet very reliable software solution designed to provide you with the ability to automatically and silently copy data from a flash drive that is connected to your PC, without prompting you for any confirmation.
# Honeypots
## Detecting and Defeating Honeypots - Detecting the presence of Honeyd Honeypot
- An attacker can identify the presence of a `honeyd honeypot` by performing `time-based TCP fingerprinting method (SYN proxy behavior)`
- Honeyd is a widely used honeypot daemon.This honeyd honeypot can respond to a remote attacker who tries to contact the SMTP service with fake responses. An attacker can identify the presence of honeyd honeypot by performing time-based TCP fingerprinting methods (SYN proxy behavior). (P.1601/5885)
## Detecting Honeypots running on VMware
- Observe the IEEE standards for the current range of MAC addresses assigned to VMWare Inc
## Detecting the presence of Snort_inline Honeypot:
- `Analyze the outgoing packets by capturing the Snort_inline modified packets` through another host system and `identifying the packet modification`
# Detecting the presence of Honeyd Honeypot:
- Perform time-based TCP Finger printing methods (SYN Proxy behavior)
# Detecting the presence of Sebek-based Honeypots:
- Sebek logs everything that is accessed via read() before transferring it to the network, causing the congestion effect. `Analyze the congestion in the network layer`
# `-sA` (TCP ACK scan)
This scan is different than the others discussed so far in that it never determines open (or even open|filtered) ports. It is used to `map out firewall rulesets, determining whether they are stateful or not` and which ports are filtered.
The ACK scan probe packet has only the ACK flag set (unless you use --scanflags). When scanning `unfiltered` systems, open and closed ports will both `return a RST packet`. Nmap then labels them as unfiltered, meaning that they are reachable by the ACK packet, but `whether they are open or closed is undetermined`. Ports that `don't respond`, or send certain ICMP error messages back (type 3, code 0, 1, 2, 3, 9, 10, or 13), are labeled `filtered`.
- ACK Flag Probe scan
ACK flag probe scanning can also be used to check the filtering system of a target.Attackers send an ACK probe packet with a random sequence number, and no response implies that the port is filtered (stateful firewall is present), whereas an RST response means that the port is not filtered.
`Nmap -sA -v <target IP address>` (P.311/295)
# Reverse Engineering Mobile Applications
Reverse engineering is the process of analyzing and extracting the source code of a software or application, and if needed, regenerating it with required modifications.Reverse engineering is used to disassemble a mobile application to analyze its design flaws and fix any bugs that are residing in it
# ABAC
- No proper attribute-based access control (ABAC) validation allows attackers to gain unauthorized access to API objects or perform actions such as viewing, updating, or deleting.
- `No ABAC Validation` - No proper attribute-based access control (ABAC) validation allows attackers to gain unauthorized access to API objects or perform actions such as viewing, updating, or deleting.
- `Business Logic Flaws` - Many APIs come with vulnerabilities in business logic .
Allow attackers to exploit legitimate workflows for malicious purposes.
- `Improper Use of CORS` - Cross-origin resource sharing (CORS) is a mechanism that enables the web browser to perform cross-domain requests; improper implementations of CORS can cause unintentional flaws .
Using the “Access-Control-Allow-Origin” header for allowing all origins on private APIs can lead to hotlinking.
- `Code Injections` - If the input is not sanitized, attackers may use code injection techniques such as SQLi and XSS to add malicious SQL statements or code to the input fields on the API.Allow attackers to steal critical information such as session cookies and user credentials.
# Evilginx
Evilginx is a man-in-the-middle attack framework used for phishing credentials and session cookies of any web service. It's core runs on Nginx HTTP server, which utilizes proxy_pass and sub_filter to proxy and modify HTTP content, while intercepting traffic between client and server.
# Phishing Tools
Phishing tools can be used by attackers to generate fake login pages to capture usernames and passwords, send spoofed emails, and obtain the victim’s IP address and session cookies.This information can further be used by the attacker, who will use it to impersonate a legitimate user and launch further attacks on the target organization.
`Tools: ShellPhish / PhishX / Modlishka / Trape / Evilginx`
# Cloud Computing Threats - Lock-in
Lock-in reflects the inability of the client to migrate from one CSP to another or in-house systems owing to the lack of tools, procedures, standard data formats, applications, and service portability. This threat is related to the inappropriate selection of a CSP, incomplete and non-transparent terms of use, lack of standard mechanisms, etc. (P.2884/2868)
- CEHv11 Cloud Computing Module Cloud Computing Threats (Page:2860)
# A Web page with an ".stm" extension
- is an .HTM file that contains server side includes (SSI). These "includes" are directives that are processed by the Web server when the page is accessed by a user. They are used to generate dynamic content. SSI Web pages can be viewed as a standard HTML page in any browser.
- Defend Against Injection Attacks - Server-Side Include Injection
Avoid using pages with file name extensions such as .stm, .shtm, and .shtml to prevent attacks.
- n order for a web server to recognize an SSI-enabled HTML file and therefore carry out these instructions, either the filename should end with a special extension, by default .shtml, .stm, .shtm, or, if the server is configured to allow this, set the execution bit of the file
# Ciphers - CAST128
- CAST- 128, also called CAST5, is a symmetric-key block cipher having a classical 12-or 16-round Feistel network with a block size of 64 bits. CAST- 128 components include large 8×32- bit S- boxes (S1, S2, S3, S4) based on bent functions, modular addition and subtraction, key-dependent rotation, and XOR operations. (P.3035/3019)
- CAST-128, also called CAST5, is a symmetric-key block cipher having a classical 12-or 16-round Feistel network with a block size of 64 bits.
# IoTSeeker (Tool)
- allows you to scan your network for known device types that could be used as unwilling participants in a distributed denial-of-service attack. With this tool you can find out if you have connected “Things” which are using the default factory password leaving them potentially vulnerable to a hostile takeover. Use the local scan output to determine which devices need to be secured or removed from the network.
- IoTSeeker to discover IoT devices that are using default credentials and are vulnerable to various hijacking attacks. IoTSeeker will scan a network for specific types of IoT devices to detect whether they are using the default, factory-set credentials. IoTSeeker focuses on HTTP/HTTPS services. (P.2633/2617)
- `IoT Inspector` - app for general management, monitor, maintenance of IoT devices
- `AT&T IoT Platform` - app for general management, monitor, maintenance of IoT devices
- `Azure IoT Central` - app for general management, monitor, maintenance of IoT devices
# Objectives of Footprinting
Draw Network Map - Combining footprinting techniques with tools such as Tracert allows the attacker to create diagrammatic representations of the target organization’s network presence. Specficially, it allows attackers to draw a map or outline of the target organization’s network infrastructure to know about the actual environment that they are going to break into. These network diagrams can guide the attacker in performing an attack. (P.114/98)
# Bob wants to ensure that Alice can check whether his message has been tampered with. He creates a checksum of the message and encrypts it using asymmetric cryptography.
What key does Bob use to encrypt the checksum for accomplishing this goal?
A. Alice's public (Correct answer)
B. His own public key
C. His own private key Most Voted
D. Alice's private key
- Encrypt the message -> Alice's public key
- Encrypt the checksum -> His own private key
- you use your private key foro sign a message (digital signature), but you use the public key of the destinatary for encrypt the message!
- Bob will digitally sign the message using his private key.
- Bob will encrypt the message using Alice's public key - So only Alice can decrypt the message.
The question talks about encryption.
Hence Answer is A - Alice's public key
# Which of the following LM hashes represent a password of less than 8 characters? (Choose two):
A. BA810DBA98995F1817306D272A9441BB
B. 44EFCE164AB921CQAAD3B435B51404EE
C. 0182BD0BD4444BF836077A718CCDF409
D. CEC52EB9C8E3455DC2265B23734E0DAC
E. B757BF5C0D87772FAAD3B435B51404EE
F. E52CAC67419A9A224A3B108F3FA6CB6D
- Any password that is shorter than 8 characters will result in the hashing of 7 null bytes, yielding the constant value of 0xAAD3B435B51404EE, hence making it easy to identify short passwords on sight.
# 73. The change of a hard drive failure is once every three years. The cost to buy a new hard drive is $300. It will require 10 hours to restore the OS and software to the new hard disk. It will require a further 4 hours to restore the database from the last backup to the new hard disk. The recovery person earns $10/hour. Calculate the SLE, ARO, and ALE. Assume the EF = 1(100%) .
What is the closest approximate cost of this replacement and recovery operation per year?
$1320
$440
$100
$146
```
- Wouldn't it be 146?
First examine the EF = 100
Hard drive fails every 3 years so divide 100/3 which = 33.333... or 33% (rounded)
There's a 33% chance the hard drive will fail each year and it will definitely fail within 3 years.
So ARO = 33% or .33
And SLE = 300 + 14 * 10
($300 for the hard drive plus $14*10 for the worker)
Then we have .33*(300+14*10)
Remember PEMDAS?
(Parenthesis, Exponent, Multiply, Divide, Add, Subtract)
So we multiply what's in the parenthesis first (14*10) which = 140
Then we add what's left in the parenthesis (300 + 140) which = 440
Lastly we multiply .33*440 which = 145.2
Closest answer is 146.
If you multiply 146 * 3 (for 3 years) it = 438, close to 440.
If I'm off please let me know.
```
## Annualized Loss Expectancy (ALE)
- Annual cost of a loss due to a risk.
- Used often in risk analysis and business impact analysis
- 📝 `ALE = ARO (Annual rate of occurrence) x SLE (Single loss expectancy)`
- **Annual rate of occurrence (ARO)**
- E.g. if it occurs every month than it's 12, if it's every second year than it's 1/2
- **Single loss expectancy (SLE)**
- Total loss value for a single asset after an exploit
- `SLE (Single Loss Expectancy) = AV (Asset Value) x EF (Exposure Factor)`
- **Asset value (AV)**
- How much would it take to replace 1 asset
- Including product prices, manhours etc.
- **Exposure Factor (EF)**
- Percentage of asset value lost if threat is realized
- Usually a subjective value
- E.g. an asset is valued at $100,000, and the Exposure Factor (EF) for this asset is 25%. The single loss expectancy (SLE) then, is 25% * $100,000, or $25,000.
- **Total cost of ownership (TCO)**
- Total cost of a mitigating safeguard
- **Return on Investment (ROI)**
- Amount of money saved by implementing a safeguard.
- 💡 Good choice if annual Total Cost of Ownership (TCO) is less than Annualized Loss Expectancy (ALE); poor choice otherwise
# Fred is the network administrator for his company. Fred is testing an internal switch.
From an external IP address, Fred wants to try and trick this switch into thinking it already has established a session with his computer .
How can Fred accomplish this?
- Fred can accomplish this by sending an IP packet with the RST/SIN bit and the source address of his computer.
- He can send an IP packet with the SYN bit and the source address of his computer.
- Fred can send an IP packet with the ACK bit set to zero and the source address of the switch.
- Fred can send an IP packet to the switch with the ACK bit and the source address of his machin (correct answer)
|
# Twitter Friends Challenge
A web app where people can test how well they know their Twitter friends.
As of this writing, it's being hosted at [TwitterFriendsChallenge.com](https://www.TwitterFriendsChallenge.com)
Feel free to DM me if you find bugs or have questions: [@jonnykalambay](https://www.twitter.com/jonnykalambay)
## Usage Overview
This app allows users to take a quiz based on the tweets of their Twitter mutuals.
It's used as follows:
1. Enter your twitter handle and it will search for and list several of your Twitter mutuals (people you follow who also follow you)
2. Choose 3 of those mutuals whose tweets you'd like to be tested on
3. Confirm your selection, and the app will generate a quiz based on the tweets of those 3 people
4. Do the quiz and then see how your score compares to that of others
5. Optional use the share button to invite others to beat your score
## Tech Overview
- This a Next.js app created with [create-next-app](https://nextjs.org/docs/api-reference/create-next-app)
- The Twitter API is interacted with using [twitter-api-v2](https://www.npmjs.com/package/twitter-api-v2)
- The quiz is generated using [Open AI](https://openai.com/api/)
- The scoreboard is managed using [Firebase](https://firebase.google.com)
- The events are tracked using Firebase and [Mixpanel](https://mixpanel.com) (Note: You don't need both. You don't even need any for the app to work. Feel free to disable/remove the code from `analytics.ts` if you don't need it.)
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
## Shameless plug for a related project
If generating quizzes from online content is something you'd like to do more of, check out: [Roshi.ai](https://www.roshi.ai/activities).
|
import React, { Dispatch, SetStateAction } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { SecretPhrase } from '@libs/crypto';
import {
SpacingSize,
TabPageContainer,
TabTextContainer,
VerticalSpaceContainer
} from '@libs/layout';
import {
SecretPhraseWordsView,
Typography,
WordPicker
} from '@libs/ui/components';
interface ConfirmSecretPhrasePageContentProps {
phrase: SecretPhrase;
setIsFormValid: Dispatch<SetStateAction<boolean>>;
setIsConfirmationSuccess: Dispatch<SetStateAction<boolean>>;
}
export function ConfirmSecretPhrasePageContent({
phrase,
setIsFormValid,
setIsConfirmationSuccess
}: ConfirmSecretPhrasePageContentProps) {
const { t } = useTranslation();
return (
<TabPageContainer>
<Typography type="captionMedium" color="contentActionCritical" uppercase>
<Trans t={t}>Step 5</Trans>
</Typography>
<VerticalSpaceContainer top={SpacingSize.Tiny}>
<Typography type="headerBig">
<Trans t={t}>Confirm your secret recovery phrase</Trans>
</Typography>
</VerticalSpaceContainer>
<TabTextContainer>
<Typography type="body" color="contentSecondary">
<Trans t={t}>
Choose the six words one by one to complete the secret recovery
phrase
</Trans>
</Typography>
</TabTextContainer>
<SecretPhraseWordsView
phrase={phrase}
confirmationMode
setIsConfirmationSuccess={setIsConfirmationSuccess}
setIsFormValid={setIsFormValid}
renderHeader={({
phrase,
hiddenWordIndexes,
selectedHiddenWordIndexes,
onHiddenWordClick,
handleResetPhrase
}) => (
<WordPicker
dataTestId="word-picker"
phrase={phrase}
hiddenWordIndexes={hiddenWordIndexes}
selectedHiddenWordIndexes={selectedHiddenWordIndexes}
onHiddenWordClick={onHiddenWordClick}
handleResetPhrase={handleResetPhrase}
/>
)}
/>
</TabPageContainer>
);
}
|
/*
* @Date: 2023-07-13
* @LastEditors: [email protected]
* @LastEditTime: 2023-07-13
* @FilePath: /algorithm/golang/931_min_falling_path_sum/min_falling_path_sum.go
*/
// Package main ...
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func minFallingPathSum(matrix [][]int) int {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
n := len(matrix)
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
copy(dp[0], matrix[0])
for i := 1; i < n; i++ {
for j := 0; j < n; j++ {
mn := dp[i-1][j]
if j > 0 {
mn = min(mn, dp[i-1][j-1])
}
if j < n-1 {
mn = min(mn, dp[i-1][j+1])
}
dp[i][j] = mn + matrix[i][j]
}
}
minVal := dp[n-1][0]
for _, val := range dp[n-1] {
if val < minVal {
minVal = val
}
}
return minVal
}
func main() {
tests := []struct {
matrix [][]int
ans int
}{
{[][]int{{2, 1, 3}, {6, 5, 4}, {7, 8, 9}}, 13},
{[][]int{{-19, 57}, {-40, -5}}, -59},
}
for _, item := range tests {
assert.Equal(&testing.T{}, minFallingPathSum(item.matrix), item.ans)
}
}
|
/*
* POFileType.test.js - test the po file type handler object.
*
* Copyright © 2021, 2023 Box, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (!POFileType) {
var POFileType = require("../POFileType.js");
var CustomProject = require("loctool/lib/CustomProject.js");
}
var p = new CustomProject({
sourceLocale: "en-US"
}, "./testfiles", {
locales:["en-GB"],
po: {
"mappings": {
"en.pot": {
"template": "[dir]/[locale].po"
},
"resources/en/US/strings.po": {
"template": "resources/[localeDir]/strings.po"
},
"**/messages.po": {
"template": "resources/[localeDir]/messages.po"
},
"**/test/str.pot": {
"template": "[dir]/[localeDir]/str.po"
},
"*.po": {
"template": "[dir]/[locale].po"
},
"**/*.pot": {
"template": "[dir]/[locale].po"
}
}
}
});
var p2 = new CustomProject({
sourceLocale: "en-US"
}, "./testfiles", {
locales:["en-GB"],
localeMap: {
"de-DE": "de"
},
po: {
mappings: {
"**/strings.po": {
"method": "copy",
"template": "resources/[localeDir]/strings.po"
}
}
}
});
describe("pofiletype", function() {
test("POFileTypeConstructor", function() {
expect.assertions(1);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
});
test("POFileTypeGetLocalizedPathLocaleDir", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'resources/[localeDir]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("resources/de/DE/strings.po");
});
test("POFileTypeGetLocalizedPathDir", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[dir]/[localeDir]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("x/y/de/DE/strings.po");
});
test("POFileTypeGetLocalizedPathDirWithLocaleMap", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({
template:'[dir]/[localeDir]/strings.po',
localeMap: {
"de-DE": "de"
}
}, "x/y/strings.po", "de-DE")).toBe("x/y/de/strings.po");
});
test("POFileTypeGetLocalizedPathDirWithLocaleMap", function() {
expect.assertions(2);
var jft = new POFileType(p2);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[dir]/[localeDir]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("x/y/de/strings.po");
});
test("POFileTypeGetLocalizedPathBasename", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[localeDir]/tr-[basename].j'}, "x/y/strings.po", "de-DE")).toBe("de/DE/tr-strings.j");
});
test("POFileTypeGetLocalizedPathFilename", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[localeDir]/tr-[filename]'}, "x/y/strings.po", "de-DE")).toBe("de/DE/tr-strings.po");
});
test("POFileTypeGetLocalizedPathExtension", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[localeDir]/tr-foobar.[extension]'}, "x/y/strings.jsn", "de-DE")).toBe("de/DE/tr-foobar.jsn");
});
test("POFileTypeGetLocalizedPathLocale", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[dir]/[locale]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("x/y/de-DE/strings.po");
});
test("POFileTypeGetLocalizedPathLocaleWithLocaleMap", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({
template: '[dir]/[locale]/strings.po',
localeMap: {
"de-DE": "de"
}
}, "x/y/strings.po", "de-DE")).toBe("x/y/de/strings.po");
});
test("POFileTypeGetLocalizedPathLocaleWithLocaleMap", function() {
expect.assertions(2);
var jft = new POFileType(p2);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[dir]/[locale]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("x/y/de/strings.po");
});
test("POFileTypeGetLocalizedPathLanguage", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[dir]/[language]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("x/y/de/strings.po");
});
test("POFileTypeGetLocalizedPathLanguageWithLocaleMap", function() {
expect.assertions(2);
var jft = new POFileType(p2);
expect(jft).toBeTruthy();
// no change
expect(jft.getLocalizedPath({template:'[dir]/[language]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("x/y/de/strings.po");
});
test("POFileTypeGetLocalizedPathRegion", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[dir]/[region]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("x/y/DE/strings.po");
});
test("POFileTypeGetLocalizedPathRegionWithLocaleMap", function() {
expect.assertions(2);
var jft = new POFileType(p2);
expect(jft).toBeTruthy();
// no region after the mapping, so it should skip the parts that don't exist
expect(jft.getLocalizedPath({template:'[dir]/[region]/strings.po'}, "x/y/strings.po", "de-DE")).toBe("x/y/strings.po");
});
test("POFileTypeGetLocalizedPathScript", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[dir]/[script]/strings.po'}, "x/y/strings.po", "zh-Hans-CN")).toBe("x/y/Hans/strings.po");
});
test("POFileTypeGetLocalizedPathLocaleUnder", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({template:'[dir]/strings_[localeUnder].po'}, "x/y/strings.po", "zh-Hans-CN")).toBe("x/y/strings_zh_Hans_CN.po");
});
test("POFileTypeGetLocalizedPathLocaleUnderWithLocaleMap", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getLocalizedPath({
template: '[dir]/strings_[localeUnder].po',
localeMap: {
"zh-Hans-CN": "zh-CN"
}
}, "x/y/strings.po", "zh-Hans-CN")).toBe("x/y/strings_zh_CN.po");
});
test("POFileTypeGetMapping1", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getMapping("x/y/messages.po")).toStrictEqual({
"template": "resources/[localeDir]/messages.po"
});
});
test("POFileTypeGetMapping2", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.getMapping("resources/en/US/strings.po")).toStrictEqual({
"template": "resources/[localeDir]/strings.po"
});
});
test("POFileTypeGetMappingNoMatch", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(!jft.getMapping("x/y/msg.pso")).toBeTruthy();
});
test("POFileTypeHandlesExtensionPOTrue", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.handles("en-US.po")).toBeTruthy();
});
test("POFileTypeHandlesExtensionPOTTrue", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.handles("strings.pot")).toBeTruthy();
});
test("POFileTypeHandlesExtensionFalse", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(!jft.handles("en-US.pohandle")).toBeTruthy();
});
test("POFileTypeHandlesNotSource", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(!jft.handles("de.po")).toBeTruthy();
});
test("POFileTypeHandlesSource", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.handles("en-US.po")).toBeTruthy();
});
test("POFileTypeHandlesTrueWithDir", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.handles("x/y/z/messages.pot")).toBeTruthy();
});
test("POFileTypeHandlesWrongDir", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(!jft.handles("x/y/z/test/de-DE.pot")).toBeTruthy();
});
test("POFileTypeHandlesRightDir", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.handles("x/y/z/test/str.pot")).toBeTruthy();
});
test("POFileTypeHandlesTrueSourceLocale", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.handles("resources/en/US/messages.pot")).toBeTruthy();
});
test("POFileTypeHandlesAlternateExtensionTrue", function() {
expect.assertions(3);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
expect(jft.handles("en-US.po")).toBeTruthy();
expect(jft.handles("en-US.pot")).toBeTruthy();
});
test("POFileTypeHandlesAlreadyLocalizedGB", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
// This matches one of the templates, but thge locale is
// not the source locale, so we don't need to
// localize it again.
expect(!jft.handles("resources/en/GB/messages.po")).toBeTruthy();
});
test("POFileTypeHandlesAlreadyLocalizedCN", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
// This matches one of the templates, but thge locale is
// not the source locale, so we don't need to
// localize it again.
expect(!jft.handles("resources/zh/Hans/CN/messages.po")).toBeTruthy();
});
test("POFileTypeHandlesNotAlreadyLocalizedenUS", function() {
expect.assertions(2);
var jft = new POFileType(p);
expect(jft).toBeTruthy();
// we figure this out from the template
expect(jft.handles("resources/en/US/messages.po")).toBeTruthy();
});
});
|
import { Flex } from "@chakra-ui/react";
import { SignupInfo } from "./SignupInfo";
import { SigupForm } from "./SignupForm";
import { useForm } from "react-hook-form";
import { useUserProvider } from "../../providers/UserContext";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
const formSchema = yup.object().shape({
name: yup.string().required("Nome obrigatório"),
email: yup
.string()
.required("E-mail obrigatório")
.email("Digite um email válido"),
password: yup
.string()
.required("Senha obrigatória")
.min(6, "No mínimo 6 caracteres"),
confirmPass: yup
.string()
.required("Confirme sua senha")
.oneOf([yup.ref("password")], "Senhas diferentes"),
});
interface SignUpData {
name: string;
email: string;
password: string;
confirmPass: string;
}
export const Signup = () => {
const {
formState: { errors },
register,
handleSubmit,
} = useForm<SignUpData>({ resolver: yupResolver(formSchema) });
const { signUp } = useUserProvider();
const handleSignUp = (data: SignUpData) => signUp(data);
return (
<Flex
alignItems="center"
height={["auto", "auto", "100vh", "100vh"]}
justifyContent="center"
margin={["25px", "25px", "20px", "0"]}
marginTop={["35px", "35px", "0", "0"]}
>
<Flex
alignItems="center"
flexDirection={["column-reverse", "column-reverse", "row", "row"]}
justifyContent="center"
width="100%"
>
<SignupInfo />
<SigupForm
errors={errors}
handleSignUp={handleSubmit(handleSignUp)}
register={register}
/>
</Flex>
</Flex>
);
};
|
MIC calculation
In its most minimal form, ``AIgarMIC`` can be used as a simple agar dilution MI calculator. Here, it is up to users to provide growth matrices for each agar dilution plate. Such users can then use :class:`aigarmic.Plate` and :class:`aigarmic.PlateSet` to calculate MICs:
>>> from aigarmic import Plate, PlateSet
>>> antibiotic = "amikacin"
>>> plate1 = Plate(drug=antibiotic,
... concentration=0,
... growth_code_matrix=[[2, 2, 2],
... [2, 2, 0],
... [0, 2, 2]])
>>> plate2 = Plate(drug=antibiotic,
... concentration=0.125,
... growth_code_matrix=[[0, 1, 2],
... [2, 2, 0],
... [0, 2, 2]])
>>> plate3 = Plate(drug=antibiotic,
... concentration=0.25,
... growth_code_matrix=[[0, 1, 2],
... [2, 2, 0],
... [0, 2, 1]])
>>> plate4 = Plate(drug=antibiotic,
... concentration=0.5,
... growth_code_matrix=[[0, 0, 2],
... [2, 0, 0],
... [0, 2, 0]])
>>> plate_set = PlateSet(plates_list=[plate1, plate2, plate3, plate4])
>>> plate_set.calculate_mic(no_growth_key_items=tuple([0, 1]))
array([[0.125, 0.125, 1. ],
[1. , 0.5 , 0.125],
[0.125, 1. , 0.25 ]])
As we can see, :func:`aigarmic.PlateSet.calculate_mic()` returns a numpy array with the MICs for each strain in the plate set. This is a 'numerical' MIC -- strains with growth in the plate with highest antibiotic concentration are reported as double the highest concentration. To convert to a more classical string MIC format, with appropriate censoring (e.g., '<0.125', '>0.5'), we can use :func:`aigarmic.PlateSet.convert_mic_matrix()`:
>>> plate_set.convert_mic_matrix(mic_format='string').tolist()
[['<0.125', '<0.125', '>0.5'], ['>0.5', '0.5', '<0.125'], ['<0.125', '>0.5', '0.25']]
|
from threading import local
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("darkgrid")
sns.set_context("paper")
plt.rcParams["font.sans-serif"]='KaiTi' #解决中文乱码问题
plt.rcParams['axes.unicode_minus']=False #解决负号无法显示的问题
df_1 = pd.read_excel('./附件1:长春市COVID-19疫情期间病毒感染人数数据.xlsx', sheet_name=0, header=0, usecols=[0]+list(range(10, 27)))
df_3 = df_1.iloc[:, 2:]
print(df_3)
df_2 = pd.read_excel('./附件1:长春市COVID-19疫情期间病毒感染人数数据.xlsx', sheet_name=1, header=0)
df_4 = df_2.iloc[:, 2:]
df_sum = df_3+df_4
df_time = df_1.iloc[:, 0]
data = pd.concat([df_time,df_sum],axis=1).values
# data.to_excel('./sum_data.xlsx')
location = ['九台区','长春新区','净月区','绿园区','朝阳区','经开区','双阳区','宽城区','南关区','汽开区','二道区','莲花山区','公主岭市','德惠市','榆树市','农安县']
plt.figure(figsize=(12, 6))
plt.title('长春市疫情发展总体趋势图', fontsize=16)
plt.xlabel("日期", fontsize=16)
plt.ylabel("总感染人数", fontsize=16)
markers = ['-*', '-o', '-^', '-+', '-x', '-+', '-v', '-^', '-p', '-d']
for i in range(1, data.shape[1]):
marker = markers[i%len(markers)]
plt.plot(data[:, 0], data[:, i], marker,label=location[i-1])
plt.legend()
plt.xticks(fontsize=17)
plt.yticks(fontsize=17)
plt.savefig('./images/分区图.png')
plt.show()
|
<div>
This is the width of the secondary display when it has the same vertical height as the primary display.<br><br>
The width of a display is equal to its height multiplied by the aspect ratio. In this case, since the displays have matching height, the width of the secondary display can be based on the primary display's height:<br><br>
<div id='eq1' class='katex'>
Secondary Display Width (W<sub>2</sub>) = L × R<sub>2</sub>
</div>
where:
<ul>
<li><em>L</em> is the physical <a onclick='selectRow(document.getElementById("selectHeight"));'>height</a> of the displays</li>
<li><em>R<sub>2</sub></em> is the aspect ratio of the secondary display (horizontal resolution divided by vertical resolution)</li>
</ul>
</div>
<div id='description_extra1' style='display:none;'>
For <span id='des_fill1'>a HRES2<span class='ratio'>∶</span>VRES2</span> secondary display with the same height as a <span id='des_fill2'>DIAG UNIT HRES × VRES</span> primary display, the width of the secondary display is:
<div id='eq3' class='katex'>
W<sub>2</sub> = L<sub>1</sub> × (H<sub>2</sub>/V<sub>2</sub>)
</div>
</div>
<div>
It is often convenient to do calculations using only the diagonal size and resolution of the displays, since these are the most readily available specifications. This can be done by substituting the equations for <a onclick='selectRow(document.getElementById("selectHeight"));'>height</a> and <a onclick='selectRow(document.getElementById("selectRatio"));'>aspect ratio</a>. This yields the following equation:
<div id='eq2' class='katex'>
W<sub>2</sub> = S<sub>1</sub> × cos(tan<sup>-1</sup>(H<sub>1</sub>/V<sub>1</sub>)) × (H<sub>2</sub>/V<sub>2</sub>)
</div>
where:
<ul>
<li><em>S<sub>1</sub></em> is the diagonal size of the primary display panel</li>
<li><em>H<sub>1</sub></em> and <em>H<sub>2</sub></em> are the horizontal resolutions of the displays</li>
<li><em>V<sub>1</sub></em> and <em>V<sub>2</sub></em> are the vertical resolutions of the displays</li>
</ul>
</div>
<div id='description_extra2' style='display:none;'>
For <span id='des_fill3'>a HRES2<span class='ratio'>∶</span>VRES2</span> secondary display with the same height as a <span id='des_fill4'>DIAG UNIT HRES × VRES</span> primary display, the width of the secondary display is:
<div id='eq4' class='katex'>
W<sub>2</sub> = S<sub>1</sub> × cos(tan<sup>-1</sup>(H<sub>1</sub>/V<sub>1</sub>)) × (H<sub>2</sub>/V<sub>2</sub>)
</div>
</div>
<script>
if (window.location.href.indexOf('DescriptionFiles') != -1) {
window.location.replace(window.location.href.substring(0, window.location.href.indexOf('DescriptionFiles')));
}
global_DescriptionFunction = function (specs) {
katex.render(
'\\textrm{Secondary Display Width}~(W_2) = L \\cdot R_2',
document.getElementById('eq1'), global_katexOptions
);
katex.render(
'W_2 = S_1 \\cdot \\Cos{\\Arctan{ \\mfrac{H_1}{V_1} }} \\cdot \\left( \\mfrac{H_2}{V_2} \\right)',
document.getElementById('eq2'), global_katexOptions
);
if (isPositive([ specs['hres'], specs['vres'], specs['diag'], specs['hres2'], specs['vres2'] ])) {
var unit = specs['unit'];
if (specs['hres2'].toString().length > 3) {
var fill_1 = a_or_an(specs['hres2']) + ' ' + specs['hres2'] + ' × ' + specs['vres2'];
$('#des_fill1').html(fill_1);
$('#des_fill3').html(fill_1);
}
else {
$('#des_fill1').html(a_or_an(specs['hres2']) + ' ' + specs['hres2'] + "<span class='ratio'>∶</span>" + specs['vres2']);
}
var fill_2 = a_or_an(specs['diag']) + ' ' + LongDivide(specs['diag'], 1, LD_1to3dp) + unit.sym(0) + ' ' + specs['hres'] + ' × ' + specs['vres'];
$('#des_fill2').html(fill_2);
$('#des_fill4').html(fill_2);
$('#description_extra1').css('display', 'block');
$('#description_extra2').css('display', 'block');
// Only print "px" after the numbers if they are greater than 2 digits, so it won't show up for aspect ratios
var px_optional = '';
if (specs['hres2'].toString().length >= 3 || specs['vres2'].toString().length >= 3) {
px_optional = '~px';
}
katex.render(
'\\begin{aligned}' +
'W_2 &= \\rm ' + LongDivide(specs['height'], 1, LD_5sf) + '~' + unit.abbr(0) +
'\\cdot \\left( \\afrac{' +
commasLaTeX(specs['hres2']) + px_optional +
'}{' +
commasLaTeX(specs['vres2']) + px_optional +
'} \\right) \\\\[5mm]' +
'&= \\rm ' + LongDivide(specs['height'], 1, LD_5sf) + '~' + unit.abbr(0) +
'\\cdot \\left(' +
LongDivide(specs['hres2'], specs['vres2'], LD_2to6dp_rep) +
'\\right)\\\\[5mm]' +
'&= \\boxed{\\rm ' +
LongDivide(Decimal(specs['hres']).div(specs['vres']).atan().cos().times(specs['diag']).times(specs['hres2']).div(specs['vres2']), 1, LD_5sf) + '~' + unit.abbr(0) +
//LongDivide(specs['diag'] * Math.cos(Math.atan(specs['hres'] / specs['vres'])) * (specs['hres2'] / specs['vres2']), 1, LD_5sf) + '~' + unit.abbr(0) +
'}' +
'\\end{aligned}',
document.getElementById('eq3'), global_katexOptions
);
katex.render(
'\\begin{aligned}' +
'W_2 &= \\rm ' + LongDivide(specs['diag'], 1, LD_4sf) + '~' + unit.abbr(0) +
' \\cdot \\Cos{\\Arctan{ \\afrac{' +
commasLaTeX(specs['hres']) +
'~px}{' +
commasLaTeX(specs['vres']) +
'~px} }} \\cdot \\left( \\afrac{' +
commasLaTeX(specs['hres2']) + px_optional +
'}{' +
commasLaTeX(specs['vres2']) + px_optional +
'} \\right) \\\\[5mm]' +
'&= \\rm ' + LongDivide(specs['diag'], 1, LD_4sf) + '~' + unit.abbr(0) +
'\\cdot(' +
LongDivide(Decimal(specs['hres']).div(specs['vres']).atan().cos(), 1, LD_4sf) +
//LongDivide(Math.cos(Math.atan(specs['hres'] / specs['vres'])), 1, LD_4sf) +
')\\cdot(' +
LongDivide(specs['hres2'], specs['vres2'], LD_2to6dp_rep) +
')\\\\[5mm]' +
'&= \\boxed{\\rm ' +
LongDivide(Decimal(specs['hres']).div(specs['vres']).atan().cos().times(specs['diag']).times(specs['hres2']).div(specs['vres2']), 1, LD_5sf) + '~' + unit.abbr(0) +
//LongDivide(specs['diag'] * Math.cos(Math.atan(specs['hres'] / specs['vres'])) * (specs['hres2'] / specs['vres2']), 1, LD_5sf) + '~' + unit.abbr(0) +
'}' +
'\\end{aligned}',
document.getElementById('eq4'), global_katexOptions
);
}
else {
$('#description_extra1').css('display', 'none');
$('#description_extra2').css('display', 'none');
}
return;
}
</script>
|
import React, { useState, useEffect } from "react";
import {MapContainer, TileLayer, Marker, Popup} from "react-leaflet";
import "./style.css";
const Map = () => {
const [companiesList, setCompaniesList] = useState([]);
useEffect(() => {
async function handleGetCompanies() {
try {
const response = await fetch("http://localhost:3333/empresas");
const data = await response.json();
setCompaniesList(data);
} catch (error) {
alert('Houve um erro ao carregar a localização do Mercados. Entre em contato com suporte.')
}
}
handleGetCompanies();
}, []);
return (
<div className="map-container">
<h1>Empresas cadastradas</h1>
<MapContainer center={[-27.5969, -48.5495]} zoom={10} scrollWheelZoom={true}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/>
{
companiesList.map(item => (
<Marker position={[item.latitude, item.longitude]}>
<Popup>
<p>Razão Social: {item.reason}</p>
<p>Nome Fantasia: {item.fantasyName}</p>
<p>CNPJ: {item.cnpj}</p>
<p>E-mail: {item.mail}</p>
</Popup>
</Marker>
))
}
</MapContainer>
</div>
)
}
export default Map;
|
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import IRecruitment from "../../../Interfaces/Recruitment";
import API from "../../../utils/API";
const Jobs = () => {
const [jobs, setJobs] = useState<IRecruitment[]>();
const navigate = useNavigate();
const getJobs = async () => {
await API.get(`recrutments`)
.then((res) => {
const filteredJobs = res.data.filter(
(job: IRecruitment) => job.number > (job.candidates ?? []).length
);
setJobs(filteredJobs);
})
.catch((err) => {
console.log(err);
});
};
function getMonthName(month: string): string {
switch (month) {
case "01":
return "January";
case "02":
return "February";
case "03":
return "March";
case "04":
return "April";
case "05":
return "May";
case "06":
return "June";
case "07":
return "July";
case "08":
return "August";
case "09":
return "September";
case "10":
return "October";
case "11":
return "November";
case "12":
return "December";
default:
return "";
}
}
useEffect(() => {
getJobs();
}, []);
return (
<section
aria-labelledby="timeline-title"
className="lg:col-start-3 w-full lg:col-span-1"
>
<div className="bg-white px-4 py-5 shadow sm:rounded-lg sm:px-6">
<h2 id="timeline-title" className="text-lg font-medium text-gray-900">
Open Jobs
</h2>
{/* Activity Feed */}
<div className="mt-6 flow-root">
<ul role="list" className="-mb-8">
{jobs ? (
jobs.map((job) => (
<li key={job.id}>
<div className="relative pb-8">
<div className="relative flex space-x-3">
<div></div>
<div className="min-w-0 flex-1 pt-1.5 flex justify-between space-x-4">
<div>
<p className="text-sm text-gray-500">
<a href="#" className="font-medium text-gray-900">
{job.position}
</a>
</p>
</div>
<div className="text-right text-sm whitespace-nowrap text-gray-500">
<time dateTime={job.created_at?.split("T")[0]}>
{getMonthName(
job.created_at
?.split("T")[0]
.split("-")[1] as string
)}{" "}
{job.created_at?.split("T")[0].split("-")[2]}{" "}
</time>
</div>
</div>
</div>
</div>
</li>
))
) : (
<h1>All jobs are closed</h1>
)}
</ul>
</div>
<div className="mt-6 flex flex-col justify-stretch">
<button
onClick={() => {
navigate("/recruitment");
}}
type="button"
className="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
View All Jobs
</button>
</div>
</div>
</section>
);
};
export default Jobs;
|
package leetcode.LC_Back;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Solution_39 {
/**
* 共享信息
*/
int n;
int[] candidates;
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
/**
* back(startIndex , sum) == 在 candidates[startIndex , ... , n-1] 中选择一个凑 sum<p>
* 注意:candidate[i] 可以<font style="color:red">重复选取</font> ==> 下一层应该 back(i) 而不是 back(i+1)
*/
public List<List<Integer>> combinationSum(int[] candidates , int target) {
this.n = candidates.length;
this.candidates = candidates;
// 预先排序,方便优化剪枝
Arrays.sort(candidates);
back(0 , target);
return res;
}
void back(int startIndex , int sum) {
// 递归边界
if (sum == 0) {
res.add(new ArrayList<>(path));
return;
}
// 遍历本层:candidates[startIndex , ... , n-1]
// 剪枝优化:若 sum < candidate[i] 则后续都有 sum < candidate[i+1 , ... , n-1] ,可以剪枝了
for (int i = startIndex ; i < n && candidates[i] <= sum ; i++) {
sum -= candidates[i];
path.add(candidates[i]);
// candidate[i] 可以重复选取
back(i , sum);
// 回溯
sum += candidates[i];
path.removeLast();
}
}
}
|
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useHistory } from "react-router-dom";
import { selectMinting, selectPinning } from "../../features/marketplace/selectors";
import { setMinting, setPinning } from "../../features/marketplace/slice";
import { selectDescription, selectFile, selectTitle } from "../../features/mintForm/selectors";
import { setFile } from "../../features/mintForm/slice";
import { selectTezos, selectUserAddress } from "../../features/tezos/selectors";
import { marketplaceContractAddress } from "../../libs/constants";
export const ImageUpload = () => {
const [image, setImage] = useState<any>(undefined);
const dispatch = useDispatch();
const file = useSelector(selectFile);
const title = useSelector(selectTitle);
const description = useSelector(selectDescription);
const userAddress = useSelector(selectUserAddress);
const pinning = useSelector(selectPinning);
const minting = useSelector(selectMinting);
const Tezos = useSelector(selectTezos);
const history = useHistory();
let upload = async () => {
try {
dispatch(setPinning(true));
const data = new FormData();
data.append("image", file);
data.append("title", title);
data.append("description", description);
if (userAddress) {
data.append("creator", userAddress);
}
console.log(userAddress);
console.log(file);
const response = await fetch(`https://energize-backend.herokuapp.com/mint`, {
method: "POST",
headers: {
contentType: 'multipart/form-data',
},
body: data,
});
if (response) {
dispatch(setPinning(false));
const data = await response.json();
if (
data.status === true &&
data.msg.metadataHash &&
data.msg.imageHash
) {
dispatch(setPinning(false));
dispatch(setMinting(true));
// mint here
const mktContract = await Tezos.wallet.at(marketplaceContractAddress);
try {
const op = await mktContract.methods
.mint('1', data.msg.metadataHash)
.send();
await op.confirmation();
history.push(`${userAddress}/tokens`)
} catch (e) {
console.log(e)
}
console.log(data);
} else {
throw "No IPFS hash";
}
} else {
throw "No response";
}
} catch (e) {
console.log("thisiserror")
console.log(e);
} finally {
console.log('eh')
dispatch(setPinning(false));
dispatch(setMinting(true));
}
}
const uploadPhoto = async (file: any) => {
const reader = new FileReader();
reader.onload = () => {
if (reader.readyState === 2) {
dispatch(setFile(file[0]));
setImage(reader.result);
}
}
console.log(file[0]);
reader.readAsDataURL(file[0]);
}
return (
<div className="flex flex-col w-1/2 p-2 align-middle justify-center ">
<div className="flex w-96 h-96 border-2 border-indigo-50 self-center justify-center ">
<img
src={image ? image : './images/placeholder_image.png'}
className={image ? "" : "w-20 h-20 self-center"}
alt="uploaded file"
></img>
</div>
<input
hidden
type="file"
id="file"
accept="image/png, image/jpeg, image/jpg"
onChange={async (e) => await uploadPhoto(e.target.files)}
/>
<button className={buttonClass} onClick={async () => { await upload() }}>Mint</button>
</div>
)
}
let buttonClass =
" flex m-4 px-4 py-1 blur-xl self-center" +
" text-pink-400 " +
" bg-gray-800 border-2 border-pink-400 "
|
import { Request, Response } from "express";
import { GetAllUserBySectorUseCase } from "./GetAllUserBySectorUseCase";
import { GetAllUserBySectorRequestSchema, GetAllUserBySectorResponseSchema, UserBySectorResponseDTO } from "./GetAllUserBySectorDTO";
import { ZodError } from "zod";
export class GetAllUserBySectorController {
constructor(private getAllUserBySector: GetAllUserBySectorUseCase) { }
async handle(request: Request, response: Response) {
try {
const { sectorId } = GetAllUserBySectorRequestSchema.parse(request.body)
const usersOrError = await this.getAllUserBySector.execute(sectorId);
if (usersOrError instanceof Error) {
return response.status(400).json(usersOrError.message);
}
const responseInFormat = GetAllUserBySectorResponseSchema.parse(usersOrError.map(user => {
const { email, name, organization_sector_id, status, created_at, updated_at } = user.props;
return { id: user.id, created_at, email, name, organization_sector_id, status, updated_at } as UserBySectorResponseDTO;
}))
return response.status(200).json(responseInFormat);
} catch (errors) {
if (errors instanceof ZodError) {
return response.status(400).json(errors.issues)
}
return response.status(400).json({ error: 'Unxpected Error', typeErrors: errors })
}
}
}
|
import React from 'react';
import { ThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import styled from 'styled-components';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import './styles/App.css';
import ChartToggleGroup from './components/ChartToggleGroup';
import { useSelector } from 'react-redux';
import UniqueGoodsChart from './components/UniqueGoodsChart';
import CategoryChart from './components/CategoryChart';
import BranchesGeo from './components/BranchesGeo';
import UniqueGoodsLeftOptions from './components/UniqueGoodsLeftOptions';
import UniqueGoodsRightOptions from './components/UniqueGoodsRightOptions';
import CategoryLeftOptions from './components/CategoryLeftOptions';
import CategoryRightOptions from './components/CategoryRightOptions';
import BranchesGeoLeftOptions from './components/BranchesGeoLeftOptions';
import { ReactComponent as MarketIcon } from './svg/market.svg';
import { ReactComponent as Analysis } from './svg/analysis.svg';
import ThemeToggler from './components/ThemeToggler';
import { CssBaseline } from '@material-ui/core';
import Lottie from 'lottie-react';
import arrowUpLottie from './lotties/arrow-up.json';
const SelectMessageBox = styled(Box)`
width: 300px;
height: 400px;
margin: 0 auto;
`;
const ChartContainer = styled.div`
width: 900px;
height: 480px;
margin: 0 auto;
@media only screen and (max-width: 1000px) {
width: 600px;
}
@media only screen and (max-width: 768px) {
width: 100vw;
}
`;
const AnalyticContainer = styled.div`
display: flex;
margin: 2rem 2.8rem;
@media only screen and (max-width: 1000px) {
flex-direction: column;
align-items: center;
margin: 0.8rem;
}
`;
const StyledMarketIcon = styled(MarketIcon)`
width: 48px;
height: 48px;
margin: 0 0.4rem;
`;
const StyledAnalysisIcon = styled(Analysis)`
width: 32px;
height: 32px;
margin: 0 0.5rem;
`;
const FlexedTypography = styled(Typography)`
display: flex;
align-items: center;
justify-content: center;
`;
function App() {
const currentChart = useSelector((state) => state.currentChart);
const theme = useSelector((state) => state.theme);
const muiTheme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: theme,
primary: {
main: '#4cc9f0',
},
secondary: {
main: '#4895ef',
},
},
overrides: {
MuiCssBaseline: {
'@global': {
body: {
transition: 'background-color 0.3s ease-in-out',
},
},
},
},
}),
[theme],
);
return (
<ThemeProvider theme={muiTheme}>
<CssBaseline />
<Box textAlign="center" aria-label="chart button group">
<Typography component="h1" variant="h2">
<StyledMarketIcon />
Sawa Supermarket
<StyledMarketIcon />
</Typography>
<FlexedTypography gutterBottom component="h2" variant="h4">
<StyledAnalysisIcon />
CMO data analysis tools
<StyledAnalysisIcon />
</FlexedTypography>
<ChartToggleGroup />
<AnalyticContainer>
{(currentChart === 'goods' && <UniqueGoodsLeftOptions />) ||
(currentChart === 'category' && <CategoryLeftOptions />) ||
(currentChart === 'map' && <BranchesGeoLeftOptions />)}
<ChartContainer>
{(currentChart === 'goods' && <UniqueGoodsChart />) ||
(currentChart === 'category' && <CategoryChart />) ||
(currentChart === 'map' && <BranchesGeo />) || (
<SelectMessageBox>
<Lottie animationData={arrowUpLottie} />
<Typography variant="h4">
Select chart type from above
</Typography>
</SelectMessageBox>
)}
</ChartContainer>
{(currentChart === 'goods' && <UniqueGoodsRightOptions />) ||
(currentChart === 'category' && <CategoryRightOptions />)}
</AnalyticContainer>
<ThemeToggler />
</Box>
</ThemeProvider>
);
}
export default App;
|
import re
import requests
from bs4 import BeautifulSoup
from ConcreteScrapers.Bnakaran.BnakaranApartmentScraper import BnakaranApartmentScraper
from Protocols import ApartmentScrapingPipeline
from Services import ImageLoader
import logging
class BnakaranScrapingPipeline(ApartmentScrapingPipeline):
def __init__(self, base_url, storage, image_loader: ImageLoader):
self.base_url = base_url
self.page = 1
self.storage = storage
self.image_loader = image_loader
self.potential_bad_api = False
self.__set_soup(base_url)
super().__init__(BnakaranApartmentScraper)
def __set_soup(self, url):
response = requests.get(url)
if response.status_code != 200 or not response.text.strip():
error = f"Bnakaran | Failed to fetch the webpage. Status code: {response.status_code}, {url}"
logging.critical(error)
raise Exception(error)
self.soup = BeautifulSoup(response.text, 'html.parser')
def navigate_to_next_page(self, max_retries=3):
retry_count = 0
while retry_count < max_retries:
previous_links = self.get_apartment_links()
self.page += 1
self.__set_soup(f"{self.base_url}?page={self.page}")
current_links = self.get_apartment_links()
if previous_links != current_links:
return # Successfully navigated to next page
retry_count += 1
logging.error(f"Bnakaran | Failed to navigate after {max_retries} retries.")
raise Exception("Bnakaran | Maximum retries exceeded for page navigation")
def scrape_apartment(self, apartment_url):
id = self.apartment_scraper.get_id(apartment_url)
apartment_scraper = self.apartment_scraper(apartment_url)
apartment_scraper.scrape()
apartment_data = apartment_scraper.values()
self.storage.append(apartment_data)
images_links = apartment_scraper.images_links()
if self.image_loader:
self.image_loader.download_images(
links=images_links,
source=BnakaranApartmentScraper.source_identifier(),
apartment_id = id
)
return
def get_apartment_links(self):
# Find all <a> tags with hrefs that end in -d followed by some numbers
apartment_links = self.soup.find_all('a', href = re.compile(r"-d\d+$"))
# Extract hrefs from the links
apartment_hrefs = set([link.get('href') for link in apartment_links])
links = [self.get_base_link() + ap_link for ap_link in apartment_hrefs]
return links
def get_base_link(self) -> str:
return "https://www.bnakaran.com"
|
import React from 'react';
import Card from './Card.jsx';
import { useDrop } from 'react-dnd';
const List = ({ name, color, plus, Tasks, setTask }) => {
const addTaskToAnotherSection = (id) => {
setTask((prev) => {
const mtasks = prev.map((t) => {
if (t.id === id) {
return { ...t, status: name };
}
return t;
});
return mtasks;
});
};
const [{ isOver }, drop] = useDrop(() => ({
accept: 'Card',
drop: (item) => {
addTaskToAnotherSection(item.id);
},
collect: (monitor) => ({
isOver: !!monitor.isOver(),
}),
}));
console.log(isOver);
return (
<div
ref={drop}
className="bg-[#F5F5F5] rounded-2xl grow px-3 pb-2 lg:w-full w-[80%] mx-auto mb-5 lg:mb-0"
>
<div className=" pt-2 left-0 bg-[#F5F5F5]">
<div className="flex items-center">
<div className="flex gap-2 grow items-center">
<svg
width="8"
height="8"
viewBox="0 0 8 8"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle cx="4" cy="4" r="4" fill={color} />
</svg>
<p className="text-[#0D062D] font-medium text-base leading-[19px] font-['Inter'] not-italic">
{name}
</p>
<p className="text-[#625F6D] font-medium text-base leading-[19px] font-['Inter'] not-italic bg-[#E0E0E0] rounded-full px-1.5">
3
</p>
</div>
{plus === 't' && (
<div className="p-1 bg-[#5030E533] rounded-md ">
<svg
xmlns="http://www.w3.org/2000/svg"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="#5030E5"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="feather feather-plus"
>
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
</div>
)}
</div>
{plus === 't' && (
<hr className="mt-2 border-2 border-[#5030E5] rounded-2xl" />
)}
{plus === 'o' && (
<hr className="mt-2 border-2 border-[#FFA500] rounded-2xl" />
)}
{plus === 'd' && (
<hr className="mt-2 border-2 border-[#76A5EA] rounded-2xl" />
)}
</div>
<div className="">
{Tasks.map((item) => item.status === name && <Card task={item} />)}
</div>
</div>
);
};
export default List;
|
import type { StayToken } from 'stays-core';
import { useMemo, useState } from 'react';
import * as Icons from 'grommet-icons';
import { Grid, Button, Box, Text } from 'grommet';
import { MessageBox } from '../MessageBox';
import { CustomText, StayVoucherQr } from '../StayVoucherQr';
import { useNavigate } from 'react-router-dom';
import { useAppState } from '../../store';
import { useContract } from '../../hooks/useContract';
import { centerEllipsis } from '../../utils/strings';
import { getNetwork } from '../../config';
import { ExternalLink } from '../ExternalLink';
// import { useGoToMessage } from '../hooks/useGoToMessage';
import { LodgingFacilityRecord } from '../../store/actions';
import styled from 'styled-components';
// import { CustomButton } from '../SearchResultCard';
import { useWindowsDimension } from '../../hooks/useWindowsDimension';
export const CustomBoldText = styled(Text)`
color: #0D0E0F;
font-family: 'Inter';
font-style: normal;
font-weight: 600;
font-size: 18px;
line-height: 24px;
`;
interface TokenViewProps extends StayToken {
facilityOwner: string | undefined;
facility: LodgingFacilityRecord | undefined;
withCloseButton?: boolean;
withRpcProvider?: boolean;
}
export const TokenView = ({
tokenId,
owner,
facilityOwner,
facility,
status,
data: {
name,
description,
image,
attributes
},
withCloseButton = true,
withRpcProvider = false
}: TokenViewProps) => {
const { winWidth } = useWindowsDimension();
const { provider, rpcProvider, ipfsNode } = useAppState();
const [, , contractError] = useContract(
withRpcProvider ? rpcProvider : provider,
ipfsNode
);
const navigate = useNavigate();
// const showMessage = useGoToMessage();
// const [cancelLoading, setCancelLoading] = useState<boolean>(false);
const [cancellationTxHash,] = useState<string | undefined>();
const [error, setError] = useState<string | undefined>();
const cancellationTxHashLink = useMemo(() => {
const network = getNetwork()
return cancellationTxHash ? `${network.blockExplorer}/tx/${cancellationTxHash}` : '#'
}, [cancellationTxHash]);
// const cancelTx = useCallback(
// async () => {
// setError(undefined);
// setCancellationTxHash(undefined);
// if (!contract) {
// return;
// }
// try {
// setCancelLoading(true);
// await contract.cancel(tokenId, undefined, setCancellationTxHash);
// setCancelLoading(false);
// // Show success message;
// showMessage(
// `Stay token #${tokenId} is successfully cancelled. All funds are fully refunded`,
// 'info'
// );
// } catch (err) {
// setError((err as Error).message || 'Unknown cancellation error');
// setCancelLoading(false);
// }
// },
// [showMessage, contract, tokenId]
// );
if (!attributes || !facility) {
return null;
}
return (
<Box
alignSelf='center'
direction='column'
pad={{ bottom: 'medium' }}
style={{ position: 'relative' }}
>
<Box
direction={winWidth > 768 ? 'row' : 'column'}
justify='between'
pad='large'
round={false}
width='65rem'
style={{ borderBottom: '1px solid black' }}
>
<Box>
<Grid
fill='horizontal'
pad='small'
columns={['small', 'auto']}
responsive
>
<Box>
<CustomBoldText weight='bold'>Status</CustomBoldText>
</Box>
<Box>
<CustomText>{status ?? 'unknown'}</CustomText>
</Box>
</Grid>
<Grid
fill='horizontal'
pad='small'
columns={['small', 'auto']}
responsive
>
<Box>
<CustomBoldText weight='bold'>Name</CustomBoldText>
</Box>
<Box>
<CustomText>{name}</CustomText>
</Box>
</Grid>
<Grid
fill='horizontal'
pad='small'
columns={['small', 'auto']}
responsive
>
<Box>
<CustomBoldText weight='bold'>Description</CustomBoldText>
</Box>
<Box>
<CustomText>{description}</CustomText>
</Box>
</Grid>
</Box>
<Box pad={{ vertical: 'small', horizontal: 'large' }} justify='between'>
{!withRpcProvider &&
<StayVoucherQr
provider={provider}
from={owner}
to={facilityOwner}
tokenId={tokenId}
onError={err => setError(err)}
name={name}
description={description}
attributes={attributes}
facility={facility}
pricePerNightWei={'0'}
/>
}
{status === 'booked' &&
<Box>
{/* <CustomButton
label={
<Box direction='row'>
<Box>
<Text>Cancel and get refund</Text>
</Box>
{cancelLoading &&
<Box pad={{ left: 'small' }}>
<Spinner />
</Box>
}
</Box>
}
disabled={cancelLoading}
onClick={cancelTx}
/> */}
{!!cancellationTxHash
? <ExternalLink
href={cancellationTxHashLink}
label={centerEllipsis(cancellationTxHash)}
/>
: null
}
</Box>
}
{withCloseButton &&
<Button
style={{
position: 'absolute',
top: 10,
right: 10
}}
icon={<Icons.Close color="plain" />}
hoverIndicator
onClick={() => navigate('/tokens', { replace: true })}
/>
}
</Box>
</Box>
<MessageBox type='error' show={!!error}>
<Box>
{error}
</Box>
</MessageBox>
<MessageBox type='error' show={!!contractError}>
<Box>
{contractError}
</Box>
</MessageBox>
</Box >
);
};
|
import { AnyState } from "xstate";
import { Path } from "./path";
import { Segment } from "./segment";
export type OnTransitionFn<TContext extends any[]> = (currentState: AnyState, ...context: TContext) => void | Promise<void>;
export type TransitionCallbackMap<TContext extends any[] = []> = {
[key: string]: OnTransitionFn<TContext>;
};
export abstract class PathRunner<TContext extends any[]> {
public async run(path: Path, ...context: TContext) {
let currentState = path.machine.initialState;
await this.onTransition(currentState, ...context);
// Use slice() to skip the initial state.
for (const segment of path.segments.slice(1)) {
currentState = await this.runSegment(segment, currentState);
await this.onTransition(currentState, ...context);
}
}
protected async runSegment(segment: Segment, state: AnyState) {
const nextState = segment.machine.transition(state, segment.event);
await this.runActions(nextState);
return nextState;
}
protected async runActions(state: AnyState) {
const { actions, context, event, meta } = state;
for (const action of actions)
if (typeof action.exec === 'function')
await action.exec(context, event, meta);
}
protected abstract onTransition(currentState: AnyState, ...context: TContext): Promise<void>;
}
|
export default class FormValidator {
constructor(settings, formEl) {
this._settings = settings;
this._formEl = formEl;
// Find Form Fields
this._inputFields = [
...formEl.querySelectorAll(this._settings.inputSelector),
];
this._submitButton = formEl.querySelector(
this._settings.submitButtonSelector
);
}
enableValidation() {
this._setEventListeners();
}
resetValidation() {
this._toggleButtonState(
this._inputFields,
this._submitButton,
this._settings
);
this._inputFields.forEach((input) => {
this._hideInputError(input);
});
}
/*═══════════════════════╕
│ INPUT FIELD FUNCTIONS │
╘═══════════════════════*/
_showInputError(inputEl) {
const errorEl = this._formEl.querySelector(`#${inputEl.id}-error`);
inputEl.classList.add(this._settings.inputErrorClass);
errorEl.classList.add(this._settings.errorClass);
errorEl.textContent = inputEl.validationMessage;
}
_hideInputError(inputEl) {
const errorEl = this._formEl.querySelector(`#${inputEl.id}-error`);
inputEl.classList.remove(this._settings.inputErrorClass);
errorEl.classList.remove(this._settings.errorClass);
errorEl.textContent = "";
}
_checkInputValidity(inputEl) {
if (!inputEl.validity.valid) {
this._showInputError(inputEl);
} else {
this._hideInputError(inputEl);
}
}
_hasInvalid(inputFields) {
return !inputFields.every((inputEl) => inputEl.validity.valid);
}
_setEventListeners() {
// Submit Listener
this._formEl.addEventListener("submit", (evt) => {
evt.preventDefault();
});
// Validate on Input Listener
this._inputFields.forEach((inputEl) => {
inputEl.addEventListener("input", () => {
this._checkInputValidity(inputEl);
this._toggleButtonState();
});
});
}
/*══════════════════╕
│ BUTTON FUNCTIONS │
╘══════════════════*/
_disableButton() {
this._submitButton.classList.add(this._settings.inactiveButtonClass);
this._submitButton.disabled = true;
}
_enableButton() {
this._submitButton.classList.remove(this._settings.inactiveButtonClass);
this._submitButton.disabled = false;
}
_toggleButtonState() {
if (this._hasInvalid(this._inputFields)) {
this._disableButton();
} else {
this._enableButton();
}
}
}
|
import { isMobile, keybind, router } from 'shared'
export default async function main() {
router([{ pathname: /novel\/\d+\/catalog/, run: injectDownloadSection }])
if (!window.ReadTools) return
resetPageEvent()
if (isMobile()) injectMovePageEvent()
else injectShortcuts()
}
export interface SyncProgressEvent {
total: number
loaded: number
progress: number
}
export interface SyncProgress {
status: 'chapter' | 'asset' | 'done'
id?: string
chapter: SyncProgressEvent
asset: SyncProgressEvent
}
type SyncResult = {
code: number
progress: SyncProgress
message: string
done: boolean
downloadURL: string
}
function injectDownloadSection() {
const bookId = window.location.pathname.match(/\d+/)![0]
document
.querySelectorAll<HTMLDivElement>('#volumes .chapter-bar')
.forEach((node, idx) => {
const api = `https://www.zhidianbao.cn:8443/qs_xq_epub/api/catalog/${bookId}/${idx}/sync`
node.innerHTML = `
<span>${node.textContent}</span>
<button class="download-btn"></button>
<div class="progress">
<div hidden></div>
</div>
`
const $btn = node.querySelector<HTMLButtonElement>('.download-btn')!
const $progress = node.querySelector<HTMLDivElement>('.progress div')!
const setProgress = (progress?: SyncProgress) => {
if (progress) {
$progress.hidden = false
const { asset, chapter } = progress
$progress.style.width =
((chapter.progress + asset.progress) * 100) / 2 + '%'
} else {
$progress.hidden = true
$progress.style.width = '0'
}
}
$btn.onclick = () => {
$btn.disabled = true
;(async function fn() {
const res: SyncResult = await fetch(api).then((res) => res.json())
setProgress(res.progress)
if (res.code !== 0) {
alert(res.message)
$btn.disabled = false
} else {
if (res.done) {
window.location.href = new URL(
res.downloadURL,
'https://www.zhidianbao.cn:8443'
).toString()
setTimeout(() => setProgress(undefined), 100)
$btn.disabled = false
} else {
setTimeout(fn, 300)
}
}
})()
}
})
}
function resetPageEvent() {
const $body = document.body
$body.onclick = (e) => {
const toolsId = ['#toptools', '#bottomtools', '#readset']
if (
toolsId.some((id) =>
document.querySelector(id)?.contains(e.target as Node)
)
) {
return
}
window.ReadPages.PageClick()
}
}
function injectMovePageEvent() {
let left: number,
startX: number,
startY: number,
diffX: number,
startTime: number,
isMoved: boolean,
direction: 'x' | 'y' | ''
const $page = document.getElementById('apage')!
const isDisabled = (e: TouchEvent) => {
return (
window.ReadTools.pagemid != 1 ||
e.touches.length > 1 ||
(window.visualViewport && window.visualViewport.scale !== 1) ||
(window.getSelection() && window.getSelection()!.toString().length > 0)
)
}
window.addEventListener('touchstart', (e) => {
if (isDisabled(e)) return
left = parseFloat($page.style.left.replace('px', '')) || 0
startX = e.touches[0].clientX
startY = e.touches[0].clientY
startTime = Date.now()
isMoved = false
direction = ''
})
window.addEventListener(
'touchmove',
(e) => {
if (isDisabled(e)) return
isMoved = true
diffX = e.touches[0].clientX - startX
let diffY = e.touches[0].clientY - startY
if (direction === '') {
direction = Math.abs(diffX) > Math.abs(diffY) ? 'x' : 'y'
}
if (direction === 'x') {
e.preventDefault()
$page.style.left = left + diffX + 'px'
$page.style.transition = 'initail'
}
},
{ passive: false }
)
window.addEventListener('touchend', (e) => {
if (isDisabled(e)) return
if (!isMoved || direction === 'y') return
const diffTime = Date.now() - startTime
const threshold =
diffTime < 300 ? 10 : document.documentElement.clientWidth * 0.3
$page.style.transition = ''
if (Math.abs(diffX) > threshold) {
const type = diffX > 0 ? 'previous' : 'next'
window.ReadPages.ShowPage(type)
if (
window.ReadPages.currentPage > window.ReadPages.totalPages ||
window.ReadPages.currentPage < 1
) {
window.ReadPages.ShowPage()
}
} else {
window.ReadPages.ShowPage()
}
})
}
function injectShortcuts() {
keybind(['a', 's', 'w', 'd', 'space', 'shift+space'], (e, key) => {
if (window.ReadTools.pagemid != 1) return
switch (key) {
case 'shift+space':
case 'a':
case 'w':
window.ReadPages.ShowPage('previous')
break
case 'space':
case 'd':
case 's':
window.ReadPages.ShowPage('next')
break
default:
break
}
})
}
|
/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IPancakeRouter02 {
function WETH() external pure returns (address);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts);
}
interface IERC20 {
function approve(address spender, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
contract SwapContract {
IPancakeRouter02 public pancakeRouter;
address public WETH;
constructor(address _routerAddress) {
pancakeRouter = IPancakeRouter02(_routerAddress);
WETH = pancakeRouter.WETH();
}
function swapTokensForETH(address _tokenIn, uint _amountIn, uint _amountOutMin, address _to) external {
IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn);
IERC20(_tokenIn).approve(address(pancakeRouter), _amountIn);
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = WETH;
pancakeRouter.swapExactTokensForETH(_amountIn, _amountOutMin, path, _to, block.timestamp);
}
function swapETHForTokens(address _tokenOut, uint _amountOutMin, address _to) external payable {
require(msg.value > 0, "Need to send some ETH");
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = _tokenOut;
pancakeRouter.swapExactETHForTokens{value: msg.value}(_amountOutMin, path, _to, block.timestamp);
}
// Just in case if the contract received any BNB, this function will be useful
function rescueBNB(address payable _to) external {
_to.transfer(address(this).balance);
}
}
|
import { safeInject } from '@/providers/inject';
import { pick } from 'lodash';
import {
ref,
computed,
InjectionKey,
provide,
reactive,
toRefs,
onBeforeMount,
} from 'vue';
import useNetwork from '@/composables/useNetwork';
import localStorageKeys from '@/constants/local-storage.keys';
import symbolKeys from '@/constants/symbol.keys';
import { lsSet } from '@/lib/utils';
import { tokenListService } from '@/services/token-list/token-list.service';
import { TokenList, TokenListMap } from '@/types/TokenList';
/** TYPES */
export interface TokenListsState {
activeListKeys: string[];
}
const { uris } = tokenListService;
const { networkId } = useNetwork();
/**
* STATE
*/
const state: TokenListsState = reactive({
activeListKeys: [uris.Balancer.Default],
});
const allTokenLists = ref({});
const tokensListPromise =
import.meta.env.MODE === 'test'
? // Only use this file in testing mode (vitest)
import('@/tests/tokenlists/tokens-5.json')
: // Use generated file in development/production mode
import(`@/assets/data/tokenlists/tokens-${networkId.value}.json`);
/**
* All active (toggled) tokenlists
*/
const activeTokenLists = computed(
(): TokenListMap => pick(allTokenLists.value, state.activeListKeys)
);
/**
* The default Balancer token list.
*/
const defaultTokenList = computed(
(): TokenList => allTokenLists.value[uris.Balancer.Default]
);
/**
* The Balancer vetted token list, contains LBP tokens.
*/
const vettedTokenList = computed(
(): TokenList => allTokenLists.value[uris.Balancer.Vetted]
);
/**
* All Balancer token lists mapped by URI.
*/
const balancerTokenLists = computed(
(): TokenListMap => pick(allTokenLists.value, uris.Balancer.All)
);
/**
* Approved token lists mapped by URI.
* Approved means tokens are compliant and can be presented in the UI.
* This excludes lists like the Balancer vetted list.
*/
const approvedTokenLists = computed(
(): TokenListMap => pick(allTokenLists.value, uris.Approved)
);
/**
* Adds a token list to the active lists which
* makes additonal tokens available in the token search modal.
*/
function toggleTokenList(uri: string): void {
if (!uris.Approved.includes(uri)) return;
if (state.activeListKeys.includes(uri)) {
// Deactivate token list
state.activeListKeys.splice(state.activeListKeys.indexOf(uri), 1);
} else {
// Activate token list
state.activeListKeys.push(uri);
}
lsSet(localStorageKeys.TokenLists.Toggled, state.activeListKeys);
}
/**
* Given a token list URI checks if the related token
* list has been toggled via the token search modal.
*/
function isActiveList(uri: string): boolean {
return state.activeListKeys.includes(uri);
}
export const tokenListsProvider = () => {
onBeforeMount(async () => {
const module = await tokensListPromise;
allTokenLists.value = module.default;
});
return {
// state
...toRefs(state),
tokensListPromise,
// computed
allTokenLists,
activeTokenLists,
defaultTokenList,
balancerTokenLists,
approvedTokenLists,
vettedTokenList,
// methods
toggleTokenList,
isActiveList,
};
};
export type TokenListsResponse = ReturnType<typeof tokenListsProvider>;
export const TokenListsProviderSymbol: InjectionKey<TokenListsResponse> =
Symbol(symbolKeys.Providers.TokenLists);
export function provideTokenLists(): TokenListsResponse {
const tokenLists = tokenListsProvider();
provide(TokenListsProviderSymbol, tokenLists);
return tokenLists;
}
export const useTokenLists = (): TokenListsResponse => {
return safeInject(TokenListsProviderSymbol);
};
|
import { Box, Button, Container, FormControl, FormHelperText, Paper, Stack, TextField } from '@mui/material';
import * as React from 'react';
import { useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import NavBar from '../components/NavBar';
import { userRegister } from '../services/api';
import { saveToken } from '../services/userLocalStorage';
type RegisterFormData = {
username: string
password: string
confirmPassword: string
};
function Register() {
const { handleSubmit, register, formState: { errors } } = useForm<RegisterFormData>();
const [showMessage, setShowMessage] = React.useState('');
const navigate = useNavigate();
const onSubmit = handleSubmit(async (data) => {
if (data.password !== data.confirmPassword) {
return setShowMessage('Senhas não coincidem');
}
const registerData = await userRegister(data);
if (registerData.token) {
saveToken(registerData.token);
navigate('/dashboard');
}
if (registerData.code) setShowMessage(registerData.response.data.message);
});
return (
<>
<NavBar />
<Box
component="section"
sx={{
height: '100vh',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
}}>
<Container sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}>
<Paper
elevation={16}
sx={{
p: 5,
height: '65vh',
width: '70vw',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Box
component="form"
sx={{
'& > :not(style)': {
m: 1,
},
}}
noValidate
autoComplete="off"
>
<Stack
sx={{ width: { xs: '98%', sm: 500 } }}
spacing={2}
alignItems="center"
>
<FormControl fullWidth>
<TextField
id='username'
label='Username'
variant='outlined'
{...register('username', { required: 'Username é necessário', minLength: 3 })}
/>
<FormHelperText error>
{errors.username?.message}
{(errors.username?.type) === 'minLength' && 'Username precisa ter ao menos 3 caracteres'}
</FormHelperText>
</FormControl>
<FormControl fullWidth>
<TextField
id='password'
type='password'
label='Senha'
variant='outlined'
{...register('password', { required: 'Senha é necessária', pattern: /^(?=.*?[A-Z])(?=.*?[0-9]).{8,}$/ })}
/>
<FormHelperText error>
{errors.password?.message}
{(errors.password?.type) === 'pattern' && 'Senha precisa ter pelo menos 8 dígitos, 1 número e 1 letra maiúscula'}
</FormHelperText>
</FormControl>
<FormControl fullWidth>
<TextField
id='confirmPassword'
type='password'
label='Confirmar senha'
variant='outlined'
{...register('confirmPassword', { required: true })}
/>
<FormHelperText error>{errors.confirmPassword?.message}</FormHelperText>
</FormControl>
<FormHelperText error>{showMessage}</FormHelperText>
<Button
variant="contained"
size="large"
onClick={onSubmit}
>
Cadastrar
</Button>
</Stack>
</Box>
</Paper>
</Container>
</Box>
</>
);
}
export default Register;
|
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_osm_plugin/flutter_osm_plugin.dart';
import 'package:flutter/material.dart';
class BuildingsApi {
final String apiUrl;
BuildingsApi(this.apiUrl);
Future<List<StaticPositionGeoPoint>> getAllBuildingsAsGeoPoints() async {
try {
final response = await http.get(Uri.parse(apiUrl));
if (response.statusCode == 200) {
final List<dynamic> buildings = json.decode(response.body)["batiments"];
final List<StaticPositionGeoPoint> geoPoints = buildings.map((building) {
final String name = building["nom"];
final List<dynamic> entryPoints = building["entree"] ?? [];
final List<GeoPoint> geoPoints = entryPoints
.map((entry) => GeoPoint(
latitude: entry["latitude"],
longitude: entry["longitude"],
))
.toList();
return StaticPositionGeoPoint(
name,
const MarkerIcon(
icon: Icon(
Icons.place,
color: Colors.blue,
size: 32,
),
),
geoPoints,
);
}).toList();
return geoPoints;
} else {
throw Exception('Failed to load buildings');
}
} catch (e) {
throw Exception('Error: $e');
}
}
Future<Map<String, dynamic>?> getBuildingByName(String buildingName) async {
final response = await http.get(Uri.parse(apiUrl));
if (response.statusCode == 200) {
final List<dynamic> buildings = json.decode(response.body)["batiments"];
final building = buildings.firstWhere(
(b) => b["nom"] == buildingName,
orElse: () => null,
);
if (building != null) {
return {
"name": building["nom"],
"position": building["entree"] ?? [],
};
} else {
return null;
}
} else {
throw Exception('Failed to load buildings');
}
}
}
|
from tools.defectdojo.defect_dojo_config import DefectDojoConfig
class DefectDojoClientV2:
base_url = "https://defectdojo.service.csnzoo.com/api/v2"
limit = 200
urls = {
"": base_url,
"products": base_url + "/products",
"product": base_url + "/products/{}",
"findings": base_url + "/findings",
"finding": base_url + "/findings/{}",
"endpoints": base_url + "/endpoints",
"endpoint": base_url + "/endpoints/{}"
}
def __init__(self):
self.config = DefectDojoConfig()
def make_request(self, url):
session = self.config.get_session()
response = session.get(url)
return response.json()
def get_call(self, url: str, query_param: dict = None):
session = self.config.get_session()
response = session.get(url, params=query_param)
return response.json()
# Get all the products
def getAllProducts(self, limit: int = None, recursiveCalls: bool = True):
if limit is None:
limit = self.limit
url = self.urls["products"]
query_params = {"limit": limit}
products = []
def check_next(res):
next_url = res["next"]
results = res["results"]
if results:
products.extend(results)
if next_url:
check_next(self.make_request(next_url))
response_json = self.get_call(url, query_params)
if recursiveCalls:
check_next(response_json)
else:
products.extend(response_json["results"])
return products
def getProduct(self, productId: int):
url = self.urls["product"].format(productId)
return self.get_call(url)
# Get all the findings
def getFindings(self, limit: int = None, recursiveCalls: bool = True):
if limit is None:
limit = self.limit
url = self.urls["findings"]
query_params = {"limit": limit}
findings = []
def check_next(res):
next_url = res["next"]
results = res["results"]
if results:
findings.extend(results)
if next_url:
check_next(self.make_request(next_url))
response_json = self.get_call(url, query_params)
if recursiveCalls:
check_next(response_json)
else:
findings.extend(response_json["results"])
return findings
def getFinding(self, findingId: int):
url = self.urls["findings"].format(findingId)
return self.get_call(url)
# Get all the Endpoints
def getEndpoints(self, limit: int = None, recursiveCalls: bool = True):
if limit is None:
limit = self.limit
url = self.urls["endpoints"]
query_params = {"limit": limit}
findings = []
def check_next(res):
next_url = res["next"]
results = res["results"]
if results:
findings.extend(results)
if next_url:
check_next(self.make_request(next_url))
response_json = self.get_call(url, query_params)
if recursiveCalls:
check_next(response_json)
else:
findings.extend(response_json["results"])
return findings
def getEndpoint(self, endpointId: int):
url = self.urls["endpoint"].format(endpointId)
return self.get_call(url)
|
class Node:
def __init__(self, data) -> None:
self.data = data
self.children = []
def busqueda_amplitud(value:str,root:Node) -> Node:
toEvaluate = [root]
evaluated = []
i = 0
while len(toEvaluate) > 0:
current = toEvaluate.pop(0)
if(current in evaluated):
print(f"El nodo {current.data} ya fue evaluado")
continue
i += 1
print(f"Iteracion {i}")
print(f"Se evalua el nodo {current.data}")
if current.data == value:
return current
evaluated.append(current)
toEvaluate.extend(current.children)
return None
# A
# / \
# B - C
# /
# D - E - F
def main():
a = Node("A")
b = Node("B")
c = Node("C")
a.children = [b,c]
b.children = [a,c]
c.children = [a,b]
d = Node("D")
e = Node("E")
f = Node("F")
b.children.append(d)
d.children.append(e)
e.children.append(f)
value_to_search = input("Ingrese el valor a buscar: ")
result = busqueda_amplitud(value_to_search,b)
if(result == None):
print("No se encontro el nodo")
else:
print(f"Se encontro el nodo {result.data}")
if __name__ == "__main__":
main()
|
import React, {useContext, useState} from "react";
import INomination from "../../model/nomination/INomination";
import {Box, Card, CardContent, CardMedia, Tooltip, Typography} from "@mui/material";
import {FavoriteBorder, Favorite} from "@mui/icons-material";
import INominationLike from "../../model/nomination/INominationLike";
import {UserContext} from "../../context/UserContext";
import useAxios from "../../hooks/useAxios";
import IMnmApiResponse from "../../model/IMnmApiResponse";
import {toast} from "react-toastify";
import INominationLikeRequest from "../../model/nomination/INominationLikeRequest";
interface NominationCardsProps {
nomination: INomination
}
export default function NominationCard(props: NominationCardsProps) {
const api = useAxios();
const {userId} = useContext(UserContext);
const poster = `https://image.tmdb.org/t/p/w500${props.nomination.posterPath}`;
const [likeCount, setLikeCount] = useState(props.nomination.nominationLikes.length);
const [nominationLiked, setNominationLiked] = useState(
props.nomination.nominationLikes.map((like) => like.userId).indexOf(userId) !== -1
);
const [nominationLikeHover, setNominationLikeHover] = useState(false);
const [likeRequestLoading, setLikeRequestLoading] = useState(false);
const handleNominationLikeToggle = () => {
if (userId && !likeRequestLoading) {
setLikeRequestLoading(true);
const likeRequest: INominationLikeRequest = {
nominationId: props.nomination.id,
userId: userId,
watchDate: "2023-01-14T18:30:00.000", // TODO :: un-hardcode these
watchType: "FIRE"
};
api.post<IMnmApiResponse<INominationLike>>("/nominationlike/manage", likeRequest)
.then(
(res) => {
if (res.data.data && res.data.status.success) {
setNominationLiked(res.data.data.enabled);
setLikeCount((prevState) => res.data.data!.enabled ? prevState + 1 : prevState - 1);
}
},
(err) => console.log(err)
)
.catch((err) => console.log(err.message))
.finally(() => setLikeRequestLoading(false));
} else {
toast.error("Please login to like a movie nomination");
}
};
const isFilledLikeIcon = () => {
return nominationLiked ? !nominationLikeHover : nominationLikeHover;
};
return (
<Box key={props.nomination.id}>
<Card variant="outlined" sx={{display: 'flex', borderRadius: '10px', width: '100%'}}>
<CardMedia
component="img"
sx={{height: '300px', width: '200px'}}
image={poster}
title={props.nomination.movieTitle}
/>
<CardContent>
<Typography>
{props.nomination.movieTitle}
</Typography>
<Typography>
Submitted By: {props.nomination.submittedBy}
</Typography>
{
isFilledLikeIcon() ?
<Favorite
onClick={handleNominationLikeToggle}
onMouseEnter={() => setNominationLikeHover(true)}
onMouseLeave={() => setNominationLikeHover(false)}
/> :
<FavoriteBorder
onClick={handleNominationLikeToggle}
onMouseEnter={() => setNominationLikeHover(true)}
onMouseLeave={() => setNominationLikeHover(false)}
/>
}
<Tooltip title={
<>
{props.nomination.nominationLikes.map(like => (
<Typography color="inherit">{like.username}</Typography>))}
</>
} arrow>
<span>{likeCount} likes</span>
</Tooltip>
</CardContent>
</Card>
</Box>
)
}
|
"""804. Unique Morse Code Words"""
from typing import List
CODES = [
".-",
"-...",
"-.-.",
"-..",
".",
"..-.",
"--.",
"....",
"..",
".---",
"-.-",
".-..",
"--",
"-.",
"---",
".--.",
"--.-",
".-.",
"...",
"-",
"..-",
"...-",
".--",
"-..-",
"-.--",
"--..",
]
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
return len({self.transform(word) for word in words})
def transform(self, word: str) -> str:
return "".join(CODES[ord(char) - ord("a")] for char in word)
|
# 0.2 Strange Device
# You head towards the hill where Cosmo detected the second cipher plate. A narrow trail branches off the main path. You hesitate for a second.
# "Don't worry, this forest is not dangerous for humans", Cosmo calms you down. "I suggest that we follow the trail - it will lead us up to that hill."
# The trail leads you deeper into the forest. After a while, you see that it starts to wind its way up. You hike the hill and see that Cosmo was right. At the top, there is a round clearing with a chest in its center that looks similar to the one in the key workshop. You know that there is another plate inside without Cosmo telling you.
# The chest is locked, but the display and buttons embedded in its lid tell you that this time, you require a code instead of a key to open it. The display shows you two lines of what seems to be a computing task. Behind the chest, some cryptic rules are engraved in a large stone:
# X; X; R; Q; -> 0
# X; Y; R; Q; -> 1
# Y; X; R; Q; -> 1
# Y; Y; R; Q; -> 1
# X; X; N; Q; -> 0
# Y; X; N; Q; -> 0
# X; Y; N; Q; -> 0
# Y; Y; N; Q; -> 1
# "Ahhh, this type of lock is quite common here", Cosmo says. "You have to solve the problem that is shown on the display. Once upon a time, the leaders of the civilization that lived here used decoding devices for these locks. Without a device, it is very hard to solve the problem, but luckily, someone left hints in the stone. There is always some logic behind the codes, and with these rules, I am sure a human like you will find the solution quickly. There are only two buttons on the chest, "0" and "1", so the solution must be a combination of them!"
# You look closer to the task shown on the display:
# YXYY; YYXY; N; Q;
# XYXX; XYYX; R; Q;
# "But this gives me two solutions - one for each line", you complain. "Which one do I have to enter?"
# "Oh, sorry, I forgot to tell you", Cosmo replies. "If there are multiple solutions, you can just concatenate them."
import pandas as pd
import numpy as np
# Prepare the cripted rules
rules = pd.DataFrame({
'X':['X', 'X', 'Y', 'Y', 'X', 'Y', 'X', 'Y'],
'Y':['X', 'Y', 'X', 'Y', 'X', 'X', 'Y', 'Y'],
'R':['R', 'R', 'R', 'R', 'N', 'N', 'N', 'N'],
'Q':['Q', 'Q', 'Q', 'Q', 'Q', 'Q', 'Q', 'Q'],
'result':[0, 1, 1, 1, 0, 0, 0, 1]
})
# Solve the first line
first_line_split = 'YXYY; YYXY; N; Q; '.split('; ')
first_line_matrix = [list(first_line_split[0]), list(first_line_split[1]), list(first_line_split[2]), list(first_line_split[3])]
first_line_result = ''
for i in range(4):
rule_result = rules[rules['X'] == first_line_matrix[0][i]]
rule_result = rule_result[rule_result['Y'] == first_line_matrix[1][i]]
rule_result = rule_result[rule_result['R'] == first_line_matrix[2][0]]
rule_result = rule_result[rule_result['Q'] == first_line_matrix[3][0]]
first_line_result += str(rule_result['result'].values[0])
print(first_line_result) # 1001
# Solve the second line
second_line_split = 'XYXX; XYYX; R; Q;'.split('; ')
second_line_matrix = [list(second_line_split[0]), list(second_line_split[1]), list(second_line_split[2]), list(second_line_split[3])]
second_line_result = ''
for i in range(4):
rule_result = rules[rules['X'] == second_line_matrix[0][i]]
rule_result = rule_result[rule_result['Y'] == second_line_matrix[1][i]]
rule_result = rule_result[rule_result['R'] == second_line_matrix[2][0]]
rule_result = rule_result[rule_result['Q'] == second_line_matrix[3][0]]
second_line_result += str(rule_result['result'].values[0])
print(second_line_result) # 0110
# Concatenate the results
solution = str(first_line_result) + str(second_line_result)
print(solution) #10010110
|
---
layout: post
title: "SpiderMonkey Newsletter (Firefox 112-113)"
date: 2023-04-14 18:00:00 +0100
---
SpiderMonkey is the JavaScript engine used in Mozilla Firefox. This newsletter gives an overview of the JavaScript and WebAssembly work we’ve done as part of the Firefox 112 and 113 Nightly release cycles.
### 🛠️ Profiler instrumentation
We're working with the performance team to improve profiler support for JIT code. This work allows us to see JS functions (and JIT optimization data) in profiles from tools such as [samply](https://github.com/mstange/samply). This makes it much easier for us to find and investigate performance issues in the engine.
* We [fixed](https://bugzilla.mozilla.org/show_bug.cgi?id=1820281) some JIT code trampolines to properly maintain frame pointers.
* We [added](https://bugzilla.mozilla.org/show_bug.cgi?id=1530552) better frame unwinding information for Windows so external profilers can iterate through JIT frames using frame pointers.
* We [added](https://bugzilla.mozilla.org/show_bug.cgi?id=1765402) Windows ETW events for mapping JIT code to method names.
* We [added](https://bugzilla.mozilla.org/show_bug.cgi?id=1820605) an optional mode for profiling that adds frame pointers to Baseline IC code.
* We [added](https://bugzilla.mozilla.org/show_bug.cgi?id=1815538) an optional mode for profiling that adds entry trampolines for scripts running in the interpreters. This makes it possible to distinguish between different scripts that are executing in the interpreter.
### 🚀 Performance
We're working on improving performance for popular web frameworks such as React. We can't list all of these improvements here, but the list below covers some of this work.
* We [optimized](https://bugzilla.mozilla.org/show_bug.cgi?id=1799023) global name lookups to use a generation counter instead of shape guards.
* We [added](https://bugzilla.mozilla.org/show_bug.cgi?id=1823811) an optimization to guess the size of objects allocated by constructor functions.
* We [rewrote](https://bugzilla.mozilla.org/show_bug.cgi?id=1483869) our implementation of `Function.prototype.bind` to be [faster](https://bugzilla.mozilla.org/show_bug.cgi?id=1820763), simpler and use [less memory](https://bugzilla.mozilla.org/show_bug.cgi?id=1483869#c28).
* We [implemented](https://bugzilla.mozilla.org/show_bug.cgi?id=1819722) monomorphic function inlining for cases where we can skip the trial inlining phase.
* We [added](https://bugzilla.mozilla.org/show_bug.cgi?id=1816981) inlining of megamorphic cache lookups to Baseline ICs in addition to Ion.
* We [made](https://bugzilla.mozilla.org/show_bug.cgi?id=1824135) our `ArraySpeciesLookup` cache more robust.
* We [made](https://bugzilla.mozilla.org/show_bug.cgi?id=1823622) some improvements to the GC's parallel marking implementation.
* We [changed](https://bugzilla.mozilla.org/show_bug.cgi?id=1825014) our self-hosted builtins to use specialized intrinsics instead of `arguments`, to eliminate unnecessary arguments object allocations in the interpreter and Baseline tiers.
### ⚡ Wasm GC
High-level programming languages currently need to bring their own GC if they want to run on WebAssembly. This can result in memory leaks because it cannot collect cycles that form with the browser. The Wasm GC [proposal](https://github.com/WebAssembly/gc/blob/main/proposals/gc/Overview.md) adds struct and array types to Wasm so these languages can use the browser's GC instead.
* We profiled the dart-barista benchmark and [fixed](https://bugzilla.mozilla.org/show_bug.cgi?id=1814519) various performance issues.
* We [optimized](https://bugzilla.mozilla.org/show_bug.cgi?id=1817385) allocation and GC [support](https://bugzilla.mozilla.org/show_bug.cgi?id=1820120) for Wasm GC objects.
* We [improved](https://bugzilla.mozilla.org/show_bug.cgi?id=1824904) the memory layout of Wasm GC objects to be more efficient.
### ⚙️ Modernizing JS modules
We're working on improving our implementation of modules. This includes supporting modules in Workers, adding support for Import Maps, and ESMification (replacing the JSM module system for Firefox internal JS code with standard ECMAScript modules).
* See the AreWeESMifiedYet [website](https://spidermonkey.dev/areweesmifiedyet/) for the status of ESMification. As of this week, almost 70% of modules have been ESMified 🎉
* We've finished most of the work for worker modules. We're hoping to [ship](https://bugzilla.mozilla.org/show_bug.cgi?id=1812591) this soon.
### 📚 Miscellaneous
* We [added](https://bugzilla.mozilla.org/show_bug.cgi?id=1773319) Stencil APIs for parsing code without using a `JSContext`.
* We [implemented](https://bugzilla.mozilla.org/show_bug.cgi?id=1804310) the `memory.discard` instruction for WebAssembly.
* We improved mitigations for fingerprinting based on [time zones](https://bugzilla.mozilla.org/show_bug.cgi?id=1709867) and [math functions](https://bugzilla.mozilla.org/show_bug.cgi?id=1823880).
* We [made](https://bugzilla.mozilla.org/show_bug.cgi?id=1817092) some [improvements](https://bugzilla.mozilla.org/show_bug.cgi?id=1816165) to the static analysis for GC hazards.
* We [implemented](https://bugzilla.mozilla.org/show_bug.cgi?id=1793962) more [parts](https://bugzilla.mozilla.org/show_bug.cgi?id=1793960) of the decorator proposal.
|
import jax
import jax.numpy as jnp
from jax import grad, value_and_grad
from jax.scipy.special import gammaln, logsumexp
from jax.scipy.linalg import expm
from functools import partial
from jax import jit
from diffrax import diffeqsolve, ODETerm, Dopri5, PIDController, ConstantStepSize, SaveAt
import logging
# We replace zeroes and infinities with small numbers sometimes
# It's sinful but that's life for you
min_float32 = jnp.finfo('float32').min
smallest_float32 = jnp.finfo('float32').smallest_normal
# calculate L, M
def lm (t, rate, prob):
return jnp.exp (-rate * t / (1. - prob))
def indels (t, rate, prob):
return 1. / lm(t,rate,prob) - 1.
# calculate derivatives of (a,b,u,q)
def derivs (t, counts, indelParams):
lam,mu,x,y = indelParams
a,b,u,q = counts
L = lm (t, lam, x)
M = lm (t, mu, y)
num = mu * (b*M + q*(1.-M))
unsafe_denom = M*(1.-y) + L*q*y + L*M*(y*(1.+b-q)-1.)
denom = jnp.where (unsafe_denom > 0., unsafe_denom, 1.) # avoid NaN gradient at zero
one_minus_m = jnp.where (M < 1., 1. - M, smallest_float32) # avoid NaN gradient at zero
d = jnp.where (unsafe_denom > 0.,
jnp.array (((mu*b*u*L*M*(1.-y)/denom - (lam+mu)*a,
-b*num*L/denom + lam*(1.-b),
-u*num*L/denom + lam*a,
((M*(1.-L)-q*L*(1.-M))*num/denom - q*lam/(1.-y))/one_minus_m))),
jnp.array ((-lam-mu,lam,lam,0.)))
# jax.debug.print("t={t} counts={counts} indelParams={indelParams} L={L} M={M} num={num} denom={denom} one_minus_m={one_minus_m} d={d}", t=t, counts=counts, indelParams=indelParams, L=L, M=M, num=num, denom=denom, one_minus_m=one_minus_m, d=d)
return d
# calculate counts (a,b,u,q) by numerical integration
def initCounts(indelParams):
return jnp.array ((1., 0., 0., 0.))
# Runge-Kutte (RK4) numerical integration routine
def integrateCounts_RK4 (t, indelParams, /, steps=100, ts=None, **kwargs):
lam,mu,x,y = indelParams
debug = kwargs.get('debug',0)
def RK4body (y, t_dt):
t, dt = t_dt
k1 = derivs(t, y, indelParams)
k2 = derivs(t+dt/2, y + dt*k1/2, indelParams)
k3 = derivs(t+dt/2, y + dt*k2/2, indelParams)
k4 = derivs(t+dt, y + dt*k3, indelParams)
y_next = y + dt*(k1 + 2*k2 + 2*k3 + k4)/6
if debug:
if debug > 1:
print(f"t={t} dt={dt} y_next={y_next.tolist()} y={y.tolist()} k1={k1.tolist()} k2={k2.tolist()} k3={k3.tolist()} k4={k4.tolist()}")
else:
print(f"t={t} dt={dt} y_next={y_next}")
return y_next, y_next
y0 = initCounts (indelParams)
gmrate = 1 / (1/lam + 1/mu)
if ts is None:
dt0 = jnp.minimum (t/steps, 1/gmrate)
ts = jnp.geomspace (dt0, t, num=steps)
ts = jnp.concatenate ([jnp.array([0]), ts])
assert len(ts) > 0
dts = jnp.ediff1d (ts)
y1, ys = jax.lax.scan (RK4body, y0, (ts[:-1],dts))
# jax.lax.scan is equivalent to...
# y1 = y0
# ys = []
# for t,dt in zip(ts[0:-1],dts):
# y1, y_out = RK4body (y1, (t,dt))
# ys.append(y_out)
return y1, jnp.concatenate([jnp.array([y0]),ys],axis=0), ts
# calculate counts (a,b,u,q) by numerical integration using diffrax
def integrateCounts_diffrax (t, indelParams, /, step = None, rtol = 1e-3, atol = 1e-3, ts = None, **kwargs):
term = ODETerm(derivs)
solver = Dopri5()
if step is None and rtol is None and atol is None:
raise Exception ("please specify step, rtol, or atol")
if step is not None:
stepsize_controller = ConstantStepSize()
else:
stepsize_controller = PIDController (rtol, atol)
y0 = initCounts(indelParams)
sol = diffeqsolve (term, solver, 0., t, step, y0, args=indelParams,
stepsize_controller=stepsize_controller,
**({'saveat': SaveAt(t0=False,t1=False,ts=ts)} if ts is not None else {}),
**kwargs)
# jax.debug.print('ts={ts} ts.shape={ts.shape} sol.ts={sol.ts} sol.ts.shape={sol.ts.shape} sol.ys={sol.ys}', sol=sol, ts=ts)
return sol.ys[-1], sol.ys, sol.ts
integrateCounts = integrateCounts_diffrax
#integrateCounts = integrateCounts_RK4
# test whether time is past threshold of alignment signal being undetectable
def alignmentIsProbablyUndetectable (t, indelParams, alphabetSize = 20):
lam,mu,x,y = indelParams
expectedMatchRunLength = 1. / (1. - jnp.exp(-mu*t))
expectedInsertions = indels(t,lam,x)
expectedDeletions = indels(t,mu,y)
kappa = 2.
return jnp.where (t > 0.,
((expectedInsertions + 1) * (expectedDeletions + 1)) > kappa * (alphabetSize ** expectedMatchRunLength),
False)
# initial transition matrix
def zeroTimeTransitionMatrix (indelParams):
lam,mu,x,y = indelParams
return jnp.array ([[1.,0.,0.],
[1.-x,x,0.],
[1.-y,0.,y]])
# convert counts (a,b,u,q) to transition matrix ((a,b,c),(f,g,h),(p,q,r))
def smallTimeTransitionMatrix (t, indelParams, /, **kwargs):
lam,mu,x,y = indelParams
# jax.debug.print("t={t} lam={lam} mu={mu} x={x} y={y}", t=t, lam=lam, mu=mu, x=x, y=y)
abuq, _abuq_by_t, _ts = integrateCounts(t,indelParams,**kwargs)
return transitionMatrixFromCounts (t, indelParams, abuq, **kwargs)
def transitionMatrixFromCounts (t, indelParams, counts, /, **kwargs):
lam,mu,x,y = indelParams
a,b,u,q = tuple(jnp.squeeze(x,axis=-1) for x in jnp.split (jnp.array(counts), indices_or_sections=4, axis=-1))
# jax.debug.print("t={t} lam={lam} mu={mu} x={x} y={y} a={a} b={b} u={u} q={q}", t=t, lam=lam, mu=mu, x=x, y=y, a=a, b=b, u=u, q=q)
L = lm(t,lam,x)
M = lm(t,mu,y)
one_minus_L = jnp.where (L < 1., 1. - L, smallest_float32) # avoid NaN gradient at zero
one_minus_M = jnp.where (M < 1., 1. - M, smallest_float32) # avoid NaN gradient at zero
mx = jnp.stack ([jnp.stack ([a,b,1-a-b]),
jnp.stack ([u*L/one_minus_L,1-(b+q*(1-M)/M)*L/one_minus_L,(b+q*(1-M)/M-u)*L/one_minus_L]),
jnp.stack ([(1-a-u)*M/one_minus_M,q,1-q-(1-a-u)*M/one_minus_M])])
if kwargs.get('norm',True):
mx = jnp.maximum (0, mx)
mx = mx / jnp.sum (mx, axis=-1, keepdims=True)
# jax.debug.print ("mx={mx}", mx=mx)
return mx
# get limiting transition matrix for large times
def largeTimeTransitionMatrix (t, indelParams):
lam,mu,x,y = indelParams
g = 1. - lm(t,lam,x)
r = 1. - lm(t,mu,y)
return jnp.array ([[(1-g)*(1-r),g,(1-g)*r],
[(1-g)*(1-r),g,(1-g)*r],
[(1-r),jnp.zeros_like(t),r]])
# get transition matrix for any given time
tMin = 1e-3
def transitionMatrix (t, indelParams, /, alphabetSize=20, **kwargs):
lam,mu,x,y = indelParams
tSafe = jnp.maximum (t, tMin)
return jnp.where (t > 0.,
jnp.where (alignmentIsProbablyUndetectable(tSafe,indelParams,alphabetSize),
largeTimeTransitionMatrix(tSafe,indelParams),
smallTimeTransitionMatrix(tSafe,indelParams,**kwargs)),
zeroTimeTransitionMatrix(indelParams))
# get dummy root transition matrix
def dummyRootTransitionMatrix():
return jnp.array ([[0,1,0],[1,1,0],[1,0,0]])
|
<template>
<div class="q-pa-none">
<q-table
v-if="props.filas.length > 0"
class="text-h6 text-grey-8 justify-center"
style="max-height: 325px"
square
flat
bordered
no-data-label="Datos no disponibles"
hide-no-data
:rows="props.filas"
:columns="props.columna"
:filter="filter"
row-key="id"
:rows-per-page-options="[0]"
v-model:pagination="pagination"
:visible-columns="columnasVisibles"
hide-header
hide-bottom
>
<template v-slot:header-cell-reclamo="props">
<q-th :props="props"> <q-icon name="add" /> Reclamo </q-th>
</template>
<template v-slot:top>
<div class="row no-wrap sq-pa-none">
<p
class="text-primary text-subtitle1"
style="font-family: 'Bebas Neue'"
>
PRODUCTOS EN FACTURA
</p>
<div class="justify-end">
<q-input
style="align-right"
input-class="text-right"
clearable
clear-icon="close"
dense
debounce="350"
borderless
color="primary"
v-model="filter"
placeholder="Buscar..."
>
<template v-slot:append>
<q-icon name="search" />
</template>
</q-input>
</div>
</div>
</template>
<template v-slot:body="props">
<q-tr :props="props">
<q-td class="col no-wrap">
<div>{{ props.row.nombre }}</div>
<div class="row justify-between">
<div><strong>Cantidad:</strong> {{ props.row.cantidad }}</div>
<div>
<strong>Lote:</strong>
{{ props.row.otra_info[0].lote }}
</div>
</div>
<div class="row justify-between">
<div>
<strong>Fecha de vencimiento:</strong>
{{ props.row.otra_info[0].fecha_vencimiento }}
</div>
<div>
<q-btn
size="sm"
color="primary"
round
dense
@click="enviarReclamo(props.row), enviarFila(props.row.id)"
icon="add"
/>
</div>
</div>
</q-td>
</q-tr>
</template>
</q-table>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { QTableProps } from 'quasar';
import { Producto } from 'components/models';
// Data
/* defined props */
const props = defineProps<{
filas: Producto[];
columna: QTableProps['columns'];
}>();
/* defined emits*/
const emit = defineEmits(['agregarReclamo', 'quitarFila']);
// Methods
const enviarReclamo = (event: Producto) => {
emit('agregarReclamo', event);
};
const enviarFila = (event: number) => {
emit('quitarFila', event);
};
const filter = ref('');
const columnasVisibles = ref(['nombre']);
const pagination = {
page: 1,
rowsPerPage: 0, // 0 means all rows
};
</script>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>FrontBidon</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="UpperPart">
<div class="LeftPart">
<div class="TitleContainer">
<img src="images/user.png" alt="" />
<h2>Informations</h2>
</div>
<form action="">
<label class="field a-field a-field_a1">
<input
class="field__input a-field__input"
id="input_nom"
placeholder="nom"
/>
<span class="a-field__label-wrap">
<span class="a-field__label">Nom</span>
</span>
<input
class="field__input a-field__input"
id="input_id"
type="hidden"
placeholder="nom"
/>
</label>
<label class="field a-field a-field_a1">
<input
class="field__input a-field__input"
id="input_prenom"
placeholder="prenom"
/>
<span class="a-field__label-wrap">
<span class="a-field__label">Prenom</span>
</span>
</label>
<label class="field a-field a-field_a1">
<input
class="field__input a-field__input"
id="input_adresse"
placeholder="adresse"
/>
<span class="a-field__label-wrap">
<span class="a-field__label">Adresse</span>
</span>
</label>
<label class="field a-field a-field_a1">
<input
class="field__input a-field__input"
id="input_date"
placeholder="date de naissance"
/>
<span class="a-field__label-wrap">
<span class="a-field__label">Date de naissance</span>
</span>
</label>
<label class="field a-field a-field_a1">
<select id="input_sexe" class="field__input a-field__input">
<option value="">--Civilité--</option>
<option value="M">Masculin</option>
<option value="F">Feminin</option>
</select>
<span class="a-field__label-wrap">
<span class="a-field__label">Civilité</span>
</span>
</label>
<div class="buttonContainer">
<button id="updateclient">Update</button>
<button id="deleteclient">Delete</button>
</div>
</form>
</div>
<div class="RightPart">
<div class="TitleContainer">
<img src="images/users.png" alt="" />
<h2>Clients</h2>
</div>
<div class="TabClient">
<table id="tableClient">
<thead>
<tr>
<th>Prenom</th>
<th>Nom</th>
<th>Adresse</th>
<th>Date de naissance</th>
<th>Civilité</th>
</tr>
</thead>
<tbody id="clientRow"></tbody>
</table>
</div>
</div>
</div>
<div class="BottomPart">
<div class="TitleContainer">
<img src="images/shop.png" alt="" />
<h2>Commandes</h2>
</div>
<table style="width:100%;">
<thead>
<tr>
<th>Produit</th>
<th>Reference</th>
<th>Date de commande</th>
<th>Quantité</th>
<th>Prix</th>
</tr>
</thead>
<tbody id="commandeRow"></tbody>
</table>
</div>
</div>
</body>
<script>
window.onload = loadData();
function loadData() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
var clients = JSON.parse(request.responseText);
document.getElementById("clientRow").innerHTML = "";
for (var i = 0; i < clients.length; i++) {
client = clients[i];
var sexe = client.civilite != null ? client.civilite : " ";
var adresse = client.adresse != null ? client.adresse : " ";
var date = new Date(client.date_naissance);
var val =
date.getFullYear() +
"-" +
(date.getMonth() + 1 < 10 ? "0" : "") +
(date.getMonth() + 1) +
"-" +
(date.getDate() + 1 < 10 ? "0" : "") +
date.getDate();
document.getElementById("clientRow").innerHTML +=
'<tr class="clientinfo" data-id="' +
client.id_client +
'"><th>' +
client.prenom +
"</th><th>" +
client.nom +
"</th><th>" +
adresse +
"</th><th>" +
val +
"</th><th> " +
sexe +
"</th></tr>";
}
var infos = document.getElementsByClassName("clientinfo");
for (var i = 0; i < infos.length; i++) {
infos[i].addEventListener(
"click",
function() {
document.getElementById("input_id").value = this.dataset.id;
document.getElementById(
"input_nom"
).value = this.children[0].innerText;
document.getElementById(
"input_prenom"
).value = this.children[1].innerText;
document.getElementById(
"input_adresse"
).value = this.children[2].innerText;
document.getElementById(
"input_date"
).value = this.children[3].innerText;
document.getElementById(
"input_sexe"
).value = this.children[4].innerText;
var cmds = document.getElementsByClassName("commandeinfo");
for (var k = 0; k < cmds.length; k++) {
if (
cmds[k].dataset.id ===
document.getElementById("input_id").value
) {
cmds[k].style.display = "table-row";
} else {
cmds[k].style.display = "none";
}
}
},
false
);
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
var commandes = JSON.parse(xhttp.responseText);
document.getElementById("commandeRow").innerHTML = "";
for (var i = 0; i < commandes.length; i++) {
commande = commandes[i];
var prix = commande.quantite * commande.prix_unitaire;
var dateCo = new Date(commande.date_commande);
var valCo =
dateCo.getFullYear() +
"-" +
(dateCo.getMonth() + 1 < 10 ? "0" : "") +
(dateCo.getMonth() + 1) +
"-" +
(dateCo.getDate() + 1 < 10 ? "0" : "") +
dateCo.getDate();
document.getElementById("commandeRow").innerHTML +=
'<tr class="commandeinfo" style="display: none;" data-id="' +
commande.id_client +
'"><th>' +
commande.libelle +
"</th><th>" +
commande.reference +
"</th><th>" +
valCo +
"</th><th>" +
commande.quantite +
"</th><th> " +
prix +
"</th></tr>";
}
}
};
xhttp.open("GET", "http://localhost:3000/commande", false);
xhttp.send();
}
};
request.open("GET", "http://localhost:3000/client", false);
request.send();
}
document
.getElementById("updateclient")
.addEventListener("click", function(e) {
e.preventDefault();
UpdateClient(
document.getElementById("input_nom").value,
document.getElementById("input_prenom").value,
document.getElementById("input_adresse").value,
document.getElementById("input_date").value,
document.getElementById("input_sexe").value,
document.getElementById("input_id").value
);
});
document
.getElementById("deleteclient")
.addEventListener("click", function(e) {
e.preventDefault();
DeleteClient(document.getElementById("input_id").value);
});
function UpdateClient(nom, prenom, adresse, date_naissance, civilite, id) {
var xhttpUpdate = new XMLHttpRequest();
var data = {};
data.nom = nom;
data.prenom = prenom;
data.adresse = adresse;
data.date_naissance = date_naissance;
data.civilite = civilite;
var json = JSON.stringify(data);
xhttpUpdate.onreadystatechange = function() {
if (xhttpUpdate.readyState == 4) {
loadData();
// document.location.reload(true);
}
};
xhttpUpdate.open("PUT", "http://localhost:3000/client/" + id, false);
xhttpUpdate.setRequestHeader(
"Content-type",
"application/json; charset=utf-8"
);
xhttpUpdate.send(json);
}
function DeleteClient(id) {
var xhttpDelete = new XMLHttpRequest();
xhttpDelete.onreadystatechange = function() {
if (xhttpDelete.readyState == 4) {
document.location.reload(true);
}
};
xhttpDelete.open("DELETE", "http://localhost:3000/client/" + id, false);
xhttpDelete.setRequestHeader(
"Content-type",
"application/json; charset=utf-8"
);
xhttpDelete.send();
}
</script>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
src="//normalize-css.googlecode.com/svn/trunk/normalize.css"
/>
<link rel="stylesheet" href="css/styles.css" />
<link rel="stylesheet" href="css/responsive.css" />
<link rel="stylesheet" href="css/a11y.css" />
<link
rel="stylesheet"
href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""
/>
<title>Restaurant Reviews</title>
</head>
<body>
<header>
<nav>
<a href="#restaurants-list" id="skip-to-content"
>Skip to Restaurant List</a
>
<a href="#neighborhoods-select" id="skip-to-content"
>Skip to Neighborhood Filter</a
>
<a href="#cuisine-select" id="skip-to-content"
>Skip to Cuisine Filter</a
>
<h1><a href="/" aria-label="Home">Restaurant Reviews</a></h1>
</nav>
</header>
<main id="maincontent">
<section id="map-container">
<div
id="map"
tabindex="0"
role="application"
aria-label="Map of restaurants"
></div>
</section>
<section>
<div class="filter-options">
<h2>Filter Results</h2>
<select
id="neighborhoods-select"
aria-label="Neighborhood Filter Listbox"
onchange="updateRestaurants()"
>
<option value="all">All Neighborhoods</option>
</select>
<select
id="cuisines-select"
aria-label="Cuisine Filter Listbox"
onchange="updateRestaurants()"
>
<option value="all">All Cuisines</option>
</select>
</div>
<ul id="restaurants-list"></ul>
</section>
</main>
<script
src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin=""
></script>
<script
type="application/javascript"
charset="utf-8"
src="js/dbhelper.js"
></script>
<script
type="application/javascript"
charset="utf-8"
src="js/main.js"
></script>
<!-- <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=places&callback=initMap"></script> -->
<footer id="footer">
Copyright (c) 2017 <a href="/"><strong>Restaurant Reviews</strong></a> All
Rights Reserved.
</footer>
</body>
</html>
|
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GFG {
// Function to print N Fibonacci Number
static void Fibonacci(int N) {
int num1 = 0, num2 = 1, count = 0;
while (count < N) {
System.out.print(num1 + " ");
int num3 = num1 + num2;
num1 = num2;
num2 = num3;
count++;
}
}
// using Stream
static List<Integer> getFibonacci(int N) {
return Stream.iterate(new int[] { 0, 1 }, t -> new int[] { t[1], t[0] + t[1] }).limit(N).map(n -> n[0])// find,
.collect(Collectors.toList());
}
static Integer recursive(int N) {
if (N <= 1)
return N;
else
return recursive(N - 1) + recursive(N - 2);
}
// Driver Code
public static void main(String args[]) {
// Given Number N
int N = 10;
List<Integer> fibonacci = getFibonacci(N);
// Function Call
Fibonacci(N); // 1
System.out.println();
fibonacci.forEach(System.out::println);// 2
for (int i = 0; i < N; i++) {
System.out.print(recursive(i) + " "); // 3
}
}
}
|
---
layout: post
title: "[파이썬] collections Counter의 most_common 활용"
description: " "
date: 2023-09-08
tags: [python,collections]
comments: true
share: true
---
Python's built-in `collections` module provides the `Counter` class, which is a powerful tool for counting and analyzing elements in an iterable. One of the most useful methods of the `Counter` class is `most_common`, which returns the most common elements and their counts in a collection.
## How to use most_common()
The `most_common` method returns a list of tuples, where each tuple consists of an element and its count. The list is sorted in descending order based on the count.
Here's an example to demonstrate the usage of `most_common`:
```python
from collections import Counter
# Create a Counter object
my_counter = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'banana'])
# Use most_common to get the most common elements
most_common_elements = my_counter.most_common()
print(most_common_elements)
```
Output:
```
[('banana', 3), ('apple', 2), ('orange', 1)]
```
In the example above, we created a `Counter` object called `my_counter` by passing a list of fruits. We then used the `most_common` method to retrieve the most common elements and their counts in descending order.
## Retrieving a specific number of common elements
By default, `most_common` returns all elements in the counter. However, you can pass an argument to specify the number of elements you want to retrieve.
Here's an example:
```python
from collections import Counter
# Create a Counter object
my_counter = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'banana'])
# Use most_common to get the top 2 most common elements
top_2_elements = my_counter.most_common(2)
print(top_2_elements)
```
Output:
```
[('banana', 3), ('apple', 2)]
```
In the above example, we passed `2` as an argument to `most_common`, so it only returned the two most common elements with their counts.
## Conclusion
The `most_common` method of the `collections.Counter` class in Python is a handy tool for finding the most common elements in a collection. It provides a simple way to analyze and extract valuable information from data.
|
#!/usr/bin/env python3
"""DB module
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import InvalidRequestError
from user import Base, User
class DB:
"""DB class
"""
def __init__(self) -> None:
"""Initialize a new DB instance
"""
self._engine = create_engine("sqlite:///a.db", echo=False)
Base.metadata.drop_all(self._engine)
Base.metadata.create_all(self._engine)
self.__session = None
@property
def _session(self) -> Session:
"""Memoized session object
"""
if self.__session is None:
DBSession = sessionmaker(bind=self._engine)
self.__session = DBSession()
return self.__session
def add_user(self, email: str, hashed_password: str) -> User:
"""
Returns User
Adds a new user using email and hashed password,
into the database
"""
new_user = User(email=email, hashed_password=hashed_password)
self._session.add(new_user)
self._session.commit()
return new_user
def find_user_by(self, **kwargs) -> User:
"""
- Returns the first row found in the users table,
as filtered by the method’s input arguments.
- method takes in arbitrary keyword arguments, which
is used for filtering
"""
if not kwargs:
raise InvalidRequestError
fields = User.__table__.columns.keys()
for key in kwargs.keys():
if key not in fields:
raise InvalidRequestError
try:
user = self._session.query(User).filter_by(**kwargs).first()
except TypeError:
raise InvalidRequestError
if user is None:
raise NoResultFound
return user
def update_user(self, user_id: str, **kwargs) -> None:
"""
locate the user to update, then will update the user’s
attributes as passed in the method’s arguments,
then commit changes to the database.
"""
user = self.find_user_by(id=user_id)
fields = User.__table__.columns.keys()
for key in kwargs.keys():
if key not in fields:
raise ValueError
for key, value in kwargs.items():
setattr(user, key, value)
self._session.commit()
|
async function loadErp(){
const data= await getGames();
renderToERP(data)
}
async function loadGameStore(){
const data= await getGames();
renderToGameStore(data)
}
function handleErpLoad(){
loadErp();
}
function handleGameStoreLoad(){
loadGameStore();
}
async function getGames(){
const {data}= await axios.get('/get-games');
return data
}
async function handleAddGame(ev){
ev.preventDefault();
const name=ev.target.elements.name.value;
const frontImg=ev.target.elements.frontImg.value;
const backImg=ev.target.elements.backImg.value;
const standardEdition=ev.target.elements.standardEdition.value;
const deluxeEdition=ev.target.elements.deluxeEdition.value;
const goldEdition=ev.target.elements.goldEdition.value;
const bundleEdition=ev.target.elements.bundleEdition.value;
const {data}= await axios.post('/add-new-game',{name,frontImg,backImg,standardEdition,deluxeEdition,goldEdition,bundleEdition});
console.log(data)
renderToERP(data);
ev.target.reset();
}
async function handleDeleteGame(ev){
ev.preventDefault();
const deletedGame=ev.target.elements.delete.value;
const {data}= await axios.post('/delete-game',{deletedGame});
renderToERP(data);
console.log(data)
ev.target.reset();
}
async function handleGetGameById(ev){
ev.preventDefault();
// console.log(id,x)
// console.dir(ev.target.elements.id)
try{
const id=ev.target.elements.id.valueAsNumber;
const x=ev.target.elements.submit.value;
const {data}= await axios.get(`/get-game-by-id?id=${id}&x=${x}`);
if (data>-1) throw new Error (`there is no id: ${id} `);
//how do i get the error message i did in the server to show
renderToERP(data);
console.log(data);
ev.target.reset();
}catch(error){
console.error(error)
}
}
async function handleUpdateGame(ev){
ev.preventDefault();
const id=ev.target.id;
//id of the game found
const name=ev.target.elements.gameName.value;
const frontImg=ev.target.elements.frontImg.value;
const backImg=ev.target.elements.backImg.value;
const standardEdition=ev.target.elements.standardEdition.valueAsNumber;
const deluxeEdition=ev.target.elements.deluxeEdition.valueAsNumber;
const goldEdition=ev.target.elements.goldEdition.valueAsNumber;
const bundleEdition=ev.target.elements.bundleEdition.valueAsNumber;
const {data}= await axios.patch('/update-game',{name,frontImg,backImg,standardEdition,deluxeEdition,goldEdition,bundleEdition,id});
console.log(data)
renderToERP(data);
}
async function handleSearchGame(ev){
const search=ev.target.value;
console.log(search);
const {data}= await axios.get(`/search-game?search=${search}`);
renderToGameStore(data);
}
function renderToERP(data){
let root=document.querySelector("#root");
let html="";
data.forEach(game=>{
html+=`
<form class="game" id="${game.id}" onsubmit="handleUpdateGame(event)">
<h3 class="gameName">${game.name}</h3>
<label for="gameName">Game Name: </label>
<input type="text" id="gameName" name="gameName" placeholder="${game.name}" required>
<label for="frontImg">Front Img Url: </label>
<input type="text" id="frontImg" name="frontImg" placeholder="${game.frontImg}" required>
<label for="backImg">Back Img Url: </label>
<input type="text" id="backImg" name="backImg" placeholder="${game.backImg}" required>
<br>
<label for="standardEdition">Standard Edition: </label>
<input type="number" id="standardEdition" name="standardEdition" placeholder="${game.standardEdition}" required>
<label for="deluxeEdition">Deluxe Edition: </label>
<input type="number" id="deluxeEdition" name="deluxeEdition" placeholder="${game.deluxeEdition}" required >
<label for="goldEdition">Gold Edition: </label>
<input type="number" id="goldEdition" name="goldEdition" placeholder="${game.goldEdition}" required>
<label for="bundleEdition">Bundle Edition: </label>
<input type="number" id="bundleEdition" name="bundleEdition" placeholder="${game.bundleEdition}" required>
<button type="submit" value="update">Update</button></form>`
})
root.innerHTML=html
};
function renderToGameStore(data){
const rootGameStore=document.querySelector("#rootGameStore");
let html="";
data.forEach(storeGame=>{
html+=`
<div class="storeGame">
<h1>${storeGame.name}</h1>
<img src="${storeGame.frontImg}" class="storeGame__img--front">
<img src="${storeGame.backImg}" class="storeGame__img--back">
<div class="storeGame__editions">
<h3 class="storeGame__editions--standardEdition"> Standard Edition ${storeGame.standardEdition} </h3>
<h3 class="storeGame__editions--deluxeEdition"> Deluxe Edition $${storeGame.deluxeEdition} </h3>
<h3 class="storeGame__editions--goldEdition"> Gold Edition $${storeGame.goldEdition} </h3>
<h3 class="storeGame__editions--bundleEdition"> Bundle Edition $${storeGame.bundleEdition} </h3>
</div>
</div>
`
})
rootGameStore.innerHTML=html;
}
|
import React, { useState } from "react";
import { NavLink } from "react-router-dom";
import {
HiOutlineHashtag,
HiOutlineHome,
HiOutlineMenu,
HiOutlinePhotograph,
HiOutlineUserGroup,
} from "react-icons/hi";
import { RiCloseLine } from "react-icons/ri";
import { logo } from "../assets";
const links = [
{ name: "Discover", to: "/", icon: HiOutlineHome },
{ name: "Around You", to: "/around-you", icon: HiOutlinePhotograph },
{ name: "Top Artists", to: "/top-artists", icon: HiOutlineUserGroup },
{ name: "Top Charts", to: "/top-charts", icon: HiOutlineHashtag },
];
const NavLinks = ({ handleClick }) => (
<div className="mt-10">
{links.map((item) => (
<NavLink
key={item.name}
to={item.to}
className="flex flex-row justify-start items-center my-8 text-sm font-medium text-gray-400 hover:text-cyan-400"
onClick={() => handleClick && handleClick()}
>
<item.icon className="w-6 h-6 mr-2" />
{item.name}
</NavLink>
))}
</div>
);
const Sidebar = () => {
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
return (
<>
<div className="md:flex hidden flex-col w-[240px] py-10 px-4 bg-[#191624]">
<img src={logo} alt="logo" className="w-full h-14 object-contain" />
<NavLinks />
</div>
{/* Mobile sidebar */}
<div className="absolute md:hidden block top-6 right-3">
{!mobileMenuOpen ? (
<HiOutlineMenu
className="w-6 h-6 mr-2 text-white"
onClick={() => setMobileMenuOpen(true)}
/>
) : (
<RiCloseLine
className="w-6 h-6 mr-2 text-white"
onClick={() => setMobileMenuOpen(false)}
/>
)}
</div>
<div
className={`absolute top-0 h-screen w-2/3 bg-gradient-to-tl from-white/10 to-[#483D8B] backdrop-blur-lg z-10 p-6 md:hidden smooth-transition ${
mobileMenuOpen ? "left-0" : "-left-full"
}`}
>
<img src={logo} alt="logo" className="w-full h-14 object-contain" />
<NavLinks handleClick={() => setMobileMenuOpen(false)} />
</div>
</>
);
};
export default Sidebar;
// import React, { useState } from "react";
// import { NavLink } from 'react-router-dom';
// import { HiOutlineHashtag, HiOutlineHome, HiOutlineMenu, HiOutlinePhotograph, HiOutlineUserGroup,} from "react-icons/hi";
// import { RiCloseLine } from "react-icons/ri";
// import { logo } from "../assets";
// import { links } from '../assets/constants';
// const NavLinks = ({ handleClick }) => (
// <div className="mt-10">
// {links.map((item) => (
// <NavLinks
// key={item.name}
// to={item.to}
// className="flex flex-row justify-start items-center my-8 text-sm font-medium text-gray-400 hover:text-cyan-400"
// onClick={() => handleClick && handleClick()}
// >
// <item.icon className="w-6 h-6 mr-2" />
// {item.name}
// </NavLinks>
// ))}
// </div>
// );
// const Sidebar = () => {
// const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
// return (
// <>
// <div className="md:flex hidden flex-col w-[240px] py-10 px-4 bg-[#191624]">
// {" "}
// {/*for mobile device */}
// <img src={logo} alt="logo" className="w-full h-14 object-contain" />
// <NavLinks />
// </div>
// {/* mobile sidebar */}
// <div className="absolute md:hidden blick top-6 right-3">
// {!mobileMenuOpen ? (
// <HiOutlineMenu className="w-6 h-6 mr-2 text-white" onClick={() => setMobileMenuOpen(true)}
// />
// ) : (
// <RiCloseLine className="w-6 h-6 mr-2 text-white" onClick={() => setMobileMenuOpen(false)}
// />
// )}
// </div>
// </>
// );
// }
// export default Sidebar;
|
class Node {
int data;
Node? left;
Node? right;
Node(this.data);
}
class BinaryTree {
Node? root;
// Insertion operation
void insert(int data) {
Node newNode = Node(data);
if (root == null) {
root = newNode;
return;
}
Node? currentNode = root;
while (true) {
if (data < currentNode!.data) {
if (currentNode.left == null) {
currentNode.left = newNode;
// return;
break;
}
currentNode = currentNode.left;
} else {
if (currentNode.right == null) {
currentNode.right = newNode;
// return;
break;
}
currentNode = currentNode.right;
}
}
}
// In-order traversal operation
void inorderTraversal(Node? node) {
if (node != null) {
inorderTraversal(node.left);
print(node.data);
inorderTraversal(node.right);
}
}
// Pre-order traversal operation
void preorderTraversal(Node? node) {
if (node != null) {
print(node.data);
preorderTraversal(node.left);
preorderTraversal(node.right);
}
}
// Post-order traversal operation
void postorderTraversal(Node? node) {
if (node != null) {
postorderTraversal(node.left);
postorderTraversal(node.right);
print(node.data);
}
}
// Deletion operation
void delete(int data) {
root = deleteNode(root, data);
}
Node? deleteNode(Node? node, int data) {
if (node == null) {
return null;
}
if (data < node.data) {
node.left = deleteNode(node.left, data);
} else if (data > node.data) {
node.right = deleteNode(node.right, data);
} else {
if (node.left == null && node.right == null) {
node = null;
} else if (node.left == null) {
node = node.right;
} else if (node.right == null) {
node = node.left;
} else {
Node temp = findMinNode(node.right)!;
node.data = temp.data;
node.right = deleteNode(node.right, temp.data);
}
}
return node;
}
Node? findMinNode(Node? node) {
while (node?.left != null) {
node = node?.left;
}
return node;
}
}
void main() {
BinaryTree tree = BinaryTree();
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(1);
tree.insert(4);
tree.insert(6);
tree.insert(8);
print("In-order traversal:");
tree.inorderTraversal(tree.root);
// print("\nPre-order traversal:");
// tree.preorderTraversal(tree.root);
// print("\nPost-order traversal:");
// tree.postorderTraversal(tree.root);
// tree.delete(5);
// print("\nIn-order traversal after deletion:");
// tree.inorderTraversal(tree.root);
}
|
const morgan = require("morgan");
const express = require("express");
const passport = require("./utils/passport");
const app = express();
const cors = require("cors");
const loginRouter = require("./routes/loginRouter");
const registerRouter = require("./routes/registerRouter");
const dashBoardRouter = require("./routes/dashboardRouter");
const expenseRouter = require("./routes/expenseRouter");
const middleware = require("./middlewares/middleware");
if (process.env.NODE_ENV === "development") {
app.use(morgan("tiny"));
}
app.get("/dashboard", (req, res) => {
res.redirect("/");
});
app.use(express.static("dist"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(middleware.requestLogger);
app.use(passport.initialize());
app.use("/api/login", loginRouter);
app.use("/api/register", registerRouter);
// add middleware auth once dashboard is finished
app.use(
"/api/dashboard",
passport.authenticate("jwt", { session: false }),
dashBoardRouter
);
app.use(
"/api/expense",
passport.authenticate("jwt", { session: false }),
expenseRouter
);
app.get(
"/test",
passport.authenticate("jwt", { session: false }),
(req, res) => {
console.log(req.user);
res.json({ message: "authorized User" });
}
);
app.use(middleware.unknownEndpoint);
app.use(middleware.errorHandler);
module.exports = app;
|
import Box from '@material-ui/core/Box';
import Container from '@material-ui/core/Container';
import Grid from '@material-ui/core/Grid';
import Tooltip from '@material-ui/core/Tooltip';
import Typography from '@material-ui/core/Typography';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import Button from '@material-ui/core/Button';
import { MAX_NUMBER_OF_FLOWS } from 'models/Flow.model';
import { Routes } from 'models/Router.model';
import { PageLoader } from 'apps/layout';
import React, { useCallback, useEffect, useState } from 'react';
import { FiPlus } from 'react-icons/fi';
import { useFormatMessage } from 'apps/intl';
import { useSelector, useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { ITemplatesList, selectTemplatesListModelValues, clearCurrentTemplate, toggleUnsavedChanges } from 'apps/Templates';
import { QATags } from 'models/QA.model';
import { useLoadTemplatesList } from '../../hooks/UseLoadTemplatesList';
import { TemplatesTable } from '../TemplatesTable/TemplatesTable';
import { useStyles } from './TemplateList.styles';
export function TemplateList() {
const classes = useStyles();
const dispatch = useDispatch();
const formatMessage = useFormatMessage();
const history = useHistory();
const templatesListValue = useSelector<any, ITemplatesList>(selectTemplatesListModelValues);
const isMobile = useMediaQuery((theme: any) => theme.breakpoints.down('sm'));
const isButtonDisabled = (templatesListValue?.rows || []).length >= MAX_NUMBER_OF_FLOWS;
const [open, setOpen] = useState(isButtonDisabled && isMobile);
const templatesList = useLoadTemplatesList();
useEffect(() => {
setOpen(isButtonDisabled && isMobile);
}, [isMobile, isButtonDisabled]);
useEffect(() => {
dispatch(clearCurrentTemplate());
dispatch(toggleUnsavedChanges(false));
}, [dispatch]);
const handleOpen = useCallback(() => {
if (templatesListValue?.rows.length >= MAX_NUMBER_OF_FLOWS) {
setOpen(true);
}
}, [templatesListValue]);
const handleClose = useCallback(() => {
if (!isMobile) {
setOpen(false);
}
}, [isMobile]);
const handleBuildMetamapButtonClick = useCallback(() => {
history.push(Routes.templates.newTemplate);
}, [history]);
if (!templatesList.isLoaded) {
return <PageLoader />;
}
return (
<Container key="content" maxWidth={false}>
<Box pt={{ xs: 2, lg: 4 }}>
<Box mb={isButtonDisabled && isMobile ? 5.6 : 0}>
<Grid container alignItems="center">
<Grid item xs={12} md={6}>
<Box mb={{ xs: 1.4, md: 0 }}>
<Typography variant="h3">{formatMessage('Templates.page.title')}</Typography>
</Box>
</Grid>
<Grid item container xs={12} md={6} justifyContent="flex-end" className={classes.buttonWrapper}>
{ !!templatesListValue?.rows.length && (
<Tooltip
enterTouchDelay={0}
placement={isMobile ? 'bottom' : 'left'}
arrow
open={open}
onOpen={handleOpen}
onClose={handleClose}
classes={{
tooltip: classes.tooltip,
popper: classes.tooltipPopper,
arrow: classes.tooltipArrow,
}}
title={formatMessage('VerificationFlow.page.tooltip')}
>
<span>
<Button
disabled={isButtonDisabled}
variant="contained"
disableElevation
onClick={handleBuildMetamapButtonClick}
className={classes.button}
data-qa={QATags.Templates.CreateNewTemplateButton}
>
<FiPlus />
{formatMessage('Templates.page.button')}
</Button>
</span>
</Tooltip>
)}
</Grid>
</Grid>
</Box>
<Box py={{ xs: 2, lg: 0 }} className={classes.table}>
<TemplatesTable onAddNewFlow={handleBuildMetamapButtonClick} />
</Box>
</Box>
</Container>
);
}
|
package com.company;
public class Rotated_Sorted_Array_With_Duplicate_Values {
static int findPivot(int[] arr){
int start = 0;
int end = arr.length-1;
while (start<=end){
int mid = start + (end-start)/2;
// 4 cases over here
if (mid < end && arr[mid]>arr[mid + 1]){
return mid;
}
if (mid > start && arr[mid]<arr[mid - 1]){
return mid-1;
}
if (arr[mid]<=arr[start]){
end = mid - 1;
}
else {
start = mid + 1;
}
}
return -1;
}
static int findPivotWithDuplicates(int[] arr){
int start = 0;
int end = arr.length-1;
while (start<=end){
int mid = start + (end-start)/2;
// 4 cases over here
if (mid < end && arr[mid]>arr[mid + 1]){
return mid;
}
if (mid > start && arr[mid]<arr[mid - 1]){
return mid-1;
}
// if elements at end , start , middle are equal then just skip the duplicates.
if (arr[mid]==arr[start] && arr[mid]==arr[end]){
// skip the duplicates.
// NOTE : what if these elements at start and end were the pivots.
// check if start is pivot.
if (arr[start] > arr[start + 1]){
return start; // start is pivot.
}
start++;
// check whether end is pivot.
if (arr[end] < arr[end - 1]){
return end - 1;
}
end--;
}
// left side is sorted so pivot should be in right.
else if (arr[start] < arr[mid] || arr[start]==arr[mid] && arr[mid]>arr[end]){
start = mid + 1;
}
else {
end = end -1;
}
}
return -1;
}
static int search(int[] nums, int target) {
int pivot = findPivotWithDuplicates(nums);
// if you did not find the pivot it means that array is not rotated.
if (pivot == -1){
// just do normal binary search
return Binarysearch(nums , target , 0 , nums.length-1);
}
// if pivot is found , you have found 2 ascending sorted arrays.
if (nums[pivot]==target){
return pivot;
}
if(target>=nums[0]){
return Binarysearch(nums , target , 0, pivot-1);
}
return Binarysearch(nums , target , pivot+1 , nums.length-1);
}
static int Binarysearch(int[] arr , int target , int start , int end){
while (start<=end){
//find the middle element.
// int mid = (start + end)/2; //possibility of start + end to exceed the limit of integer in java.
// better way to find mid:
int mid = start + (end - start)/2;
if (target < arr[mid]){
end = mid - 1;
}
else if (target> arr[mid]){
start = mid + 1;
}
else {
// ans found.
return mid;
}
}
return -1;
}
public static void main(String[] args) {
}
}
|
const Critters = require("critters");
const { join } = require("path");
const fs = require("fs");
const { parse } = require("node-html-parser");
const CryptoJS = require("crypto-js");
const { minify } = require("csso");
// Recursive function to get files
function getHTMLFiles(dir, files = []) {
// Get an array of all files and directories in the passed directory using fs.readdirSync
const fileList = fs.readdirSync(dir);
// Create the full path of the file/directory by concatenating the passed directory and file/directory name
for (const file of fileList) {
const name = `${dir}/${file}`;
// Check if the current file/directory is a directory using fs.statSync
if (fs.statSync(name).isDirectory()) {
// If it is a directory, recursively call the getFiles function with the directory path and the files array
getHTMLFiles(name, files);
} else {
// If it is an HTML file, push the full path to the files array
if (name.endsWith("html")) {
files.push(name);
}
}
}
return files;
}
async function criticalCSS() {
const currentFolder = join(process.cwd(), ".next");
const files = getHTMLFiles(currentFolder);
const critters = new Critters({
path: currentFolder,
fonts: true, // inline critical font rules (may be better for performance)
});
for (const file of files) {
try {
const html = fs.readFileSync(file, "utf-8");
const DOMBeforeCritters = parse(html);
const uniqueImportantStyles = new Set();
// first find all inline styles and add them to Set
for (const style of DOMBeforeCritters.querySelectorAll("style")) {
uniqueImportantStyles.add(style.innerHTML);
}
const pathPatterns = {
real: "/static/css",
original: "/_next/static/css",
};
const changedToRealPath = html.replaceAll(
pathPatterns.original,
pathPatterns.real
);
const inlined = await critters.process(changedToRealPath);
const DOMAfterCritters = parse(inlined);
// merge all styles form existing <style/> tags into one string
const importantCSS = Array.from(uniqueImportantStyles).join("");
const body = DOMAfterCritters.querySelector("body");
if (importantCSS.length > 0) {
const attachedStylesheets = new Set();
const stylesheets = [];
// find all <link/> tags with styles, get href from them and remove them from HTML
for (const link of DOMAfterCritters.querySelectorAll("link")) {
if (
link.attributes?.as === "style" ||
link.attributes?.rel === "stylesheet"
) {
attachedStylesheets.add(link.getAttribute("href"));
link.remove();
}
}
// go through found stylesheets: read file with CSS and push CSS string to stylesheets array
for (const stylesheet of Array.from(attachedStylesheets)) {
const stylesheetStyles = fs.readFileSync(
join(currentFolder, stylesheet)
);
stylesheets.push(stylesheetStyles);
}
// Merge all stylesheets in one, add importantCSS in the end to persist specificity
const allInOne = stylesheets.join("") + importantCSS;
// using the hash, we will only create a new file if a file with that content does not exist
const hash = CryptoJS.MD5(CryptoJS.enc.Latin1.parse(allInOne));
const inlinedStylesPath = `/static/css/styles.${hash}.css`;
fs.writeFileSync(
join(currentFolder, inlinedStylesPath),
// minification is optional here, it doesn't affect performance -- it is a lazy loaded CSS stylesheet, it only affects payload
minify(allInOne).css
);
if (body) {
body.insertAdjacentHTML(
"beforeend",
`<link rel="stylesheet" href="/_next${inlinedStylesPath}" />`
);
}
}
fs.writeFileSync(file, DOMAfterCritters.toString());
} catch (error) {
console.log(error);
}
}
}
criticalCSS();
|
package ArchivosTexto;
/**
*
* @author aleag
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
public class CrearXML {
public static void main(String[] args) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element persona = doc.createElement("persona");
persona.setAttribute("profesion", "cantante");
Element nombre = doc.createElement("nombre");
Text nombreText = doc.createTextNode("Elsa");
nombre.appendChild(nombreText);
Element mujer = doc.createElement("mujer");
Element fechaDeNacimiento = doc.createElement("fecha_de_nacimiento");
Element mes = doc.createElement("mes");
Text mesText = doc.createTextNode("6");
mes.appendChild(mesText);
Element ano = doc.createElement("ano");
Text anoText = doc.createTextNode("1996");
ano.appendChild(anoText);
fechaDeNacimiento.appendChild(mes);
fechaDeNacimiento.appendChild(ano);
Element ciudad = doc.createElement("ciudad");
Text ciudadText = doc.createTextNode("Pamplona");
ciudad.appendChild(ciudadText);
persona.appendChild(nombre);
persona.appendChild(mujer);
persona.appendChild(fechaDeNacimiento);
persona.appendChild(ciudad);
doc.appendChild(persona);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("persona.xml"));
transformer.transform(source, result);
System.out.println("Archivo XML creado exitosamente.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/* eslint-disable no-param-reassign */
/* eslint-disable no-shadow */
import React from 'react';
import { View } from 'react-native';
import { useSelector } from 'react-redux';
import {
Button,
Layout,
Text,
Spinner,
Input,
} from '@ui-kitten/components';
import {
USER_DETAILS,
} from 'utils/constants';
import { t } from 'services/i18n';
import { Formik } from 'formik';
import handleLogEvent from 'utils/handleLogEvent';
import * as Yup from 'yup';
import KeyboardAvoidingView from 'components/KeyBoardAvoidingView';
import PropTypes from 'prop-types';
import moment from 'moment';
import 'moment/locale/ar-dz';
import commonStyles from 'utils/commonStyles';
import { updateUser } from 'api';
import styles from './styles';
const ValidateUpload = ({ route, navigation }) => {
const { password } = route.params;
const currLang = useSelector(state => state.language.language);
const {
idNumber,
cardNumber,
fullName,
nationality,
sex,
dateOfBirth,
cardExpiryDate,
editableFields,
showFields,
} = useSelector(state => state.registration);
const { userId } = useSelector(state => state.application.currentUser);
const processErrors = (err, t) => {
const result = {};
const { code } = err;
if (code) {
if (code === 'registration_session_age_validate_exception') {
result.dateOfBirth = t('errors.ageRequirements');
}
if (code === 'details_not_valid') {
result.fullName = t('errors.nameNotValid');
}
}
return result;
};
const prepareData = values => {
values.fullName = values.fullName.trim();
const [day, month, year] = values.dateOfBirth.split('/');
// Date constructor takes in 0-indexed month
const dateOfBirth = year
? moment(new Date(year, Number(month) - 1, day)).format('YYYY-MM-DD')
: null;
return {
userId,
fullName: values.fullName,
dateOfBirth,
cardExpiryDate,
idNumber: values.idNumber,
cardNumber: values.cardNumber,
};
};
return (
<Layout
style={styles.form}
level="1"
>
<KeyboardAvoidingView>
<View style={styles.form}>
<Formik
initialValues={{
dateOfBirth,
idNumber,
cardNumber,
fullName,
nationality,
sex,
cardExpiryDate,
}}
onSubmit={async (values, actions) => {
try {
const data = prepareData(values);
await updateUser(data);
actions.setStatus('success');
navigation.navigate('Welcome', { password });
// import handleLogEvent from 'utils/handleLogEvent';
await handleLogEvent('SpotiiMobileIDVerified');
} catch (err) {
const { errors = {} } = err || {};
actions.setErrors(processErrors(errors, t));
}
}}
validationSchema={Yup.object().shape({
fullName: editableFields.includes(USER_DETAILS.NAME)
? Yup.string()
.min(2, t('errors.nameMin'))
.matches(/^([^0-9\u0660-\u0669]*)$/, {
message: t('errors.numbersNotAllowedInName'),
excludeEmptyString: false,
})
.matches(/^([^\u0621-\u064A]*)$/, {
message: t('errors.englishNamesOnly'),
excludeEmptyString: false,
})
.matches(/^[a-z\u00c0-\u017f-' ]*$/i, {
message: t('errors.validName'),
excludeEmptyString: false,
})
.required(t('errors.nameRequired'))
: Yup.string(),
dateOfBirth: editableFields.includes(USER_DETAILS.DOB)
? Yup.string().required(t('errors.dobRequired'))
: Yup.string(),
idNumber: editableFields.includes(USER_DETAILS.ID_NUMBER)
? Yup.string()
.matches(/^[0-9]{8,15}$/, {
message: t('errors.validIdNumber'),
excludeEmptyString: false,
})
.required(t('errors.idNumberRequired'))
: Yup.string(),
cardNumber: editableFields.includes(USER_DETAILS.CARD_NUMBER)
? Yup.string()
.matches(/^[0-9]{8,15}$/, {
message: t('errors.validCardNumber'),
excludeEmptyString: false,
})
.required(t('errors.cardNumberRequired'))
: Yup.string(),
cardExpiryDate: editableFields.includes(USER_DETAILS.CARD_EXPIRY)
? Yup.string().required(t('errors.cardExpiryDateRequired'))
: Yup.string(),
})}
>
{({
isValid,
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit,
setFieldValue,
submitCount,
// eslint-disable-next-line arrow-body-style
}) => {
return (
<>
<View style={styles.header}>
<Text style={styles.text} category="h2">{t('common.personalDetails')}</Text>
<Text style={[styles.subText, { textAlign: 'center', marginTop: '2%' }]}>{t('common.personalDetailsSub')}</Text>
</View>
{showFields.includes(USER_DETAILS.NAME) ? (
<Input
placeholder={t('common.fullName')}
style={[styles.inputStyles]}
textAlign={currLang === 'ar' ? 'right' : 'left'}
value={values.fullName}
onChangeText={handleChange('fullName')}
onBlur={handleBlur('fullName')}
caption={() => (errors.fullName && submitCount > 0 ? (
<Text status="danger" style={[styles.caption, { textAlign: currLang === 'ar' ? 'right' : 'left' }]} category="p1">
{errors.fullName}
</Text>
) : null)}
disabled={!editableFields.includes(USER_DETAILS.NAME)}
/>
) : null}
{showFields.includes(USER_DETAILS.ID_NUMBER) ? (
<Input
placeholder={t('common.idNumber')}
style={[styles.inputStyles]}
textAlign={currLang === 'ar' ? 'right' : 'left'}
value={values.idNumber}
onChangeText={handleChange('idNumber')}
onBlur={handleBlur('idNumber')}
caption={() => (errors.idNumber && submitCount > 0 ? (
<Text status="danger" style={[styles.caption, { textAlign: currLang === 'ar' ? 'right' : 'left' }]} category="p1">
{errors.idNumber}
</Text>
) : null)}
disabled={!editableFields.includes(USER_DETAILS.ID_NUMBER)}
/>
) : null}
{showFields.includes(USER_DETAILS.CARD_NUMBER) ? (
<Input
placeholder={t('common.cardNumber')}
style={[styles.inputStyles]}
textAlign={currLang === 'ar' ? 'right' : 'left'}
value={values.cardNumber}
onChangeText={handleChange('cardNumber')}
onBlur={handleBlur('cardNumber')}
caption={() => (errors.cardNumber && submitCount > 0 ? (
<Text status="danger" style={[styles.caption, { textAlign: currLang === 'ar' ? 'right' : 'left' }]} category="p1">
{errors.cardNumber}
</Text>
) : null)}
disabled={!editableFields.includes(USER_DETAILS.CARD_NUMBER)}
/>
) : null}
{showFields.includes(USER_DETAILS.CARD_EXPIRY) ? (
<Input
placeholder={t('common.cardExpiryDate')}
style={[styles.inputStyles]}
textAlign={currLang === 'ar' ? 'right' : 'left'}
value={values.cardExpiryDate}
onChangeText={handleChange('cardExpiryDate')}
onBlur={handleBlur('cardExpiryDate')}
caption={() => (errors.cardExpiryDate && submitCount > 0 ? (
<Text status="danger" style={[styles.caption, { textAlign: currLang === 'ar' ? 'right' : 'left' }]} category="p1">
{errors.cardExpiryDate}
</Text>
) : null)}
disabled={!editableFields.includes(USER_DETAILS.CARD_EXPIRY)}
/>
) : null}
{showFields.includes(USER_DETAILS.DOB) ? (
<Input
placeholder="DD/MM/YYYY"
style={[styles.inputStyles]}
textAlign={currLang === 'ar' ? 'right' : 'left'}
value={values.dateOfBirth}
onChangeText={handleChange('dateOfBirth')}
onBlur={handleBlur('dateOfBirth')}
caption={() => (errors.dateOfBirth && submitCount > 0 ? (
<Text status="danger" style={[styles.caption, { textAlign: currLang === 'ar' ? 'right' : 'left' }]} category="p1">
{errors.dateOfBirth}
</Text>
) : null)}
disabled={!editableFields.includes(USER_DETAILS.DOB)}
/>
) : null}
<Button
style={styles.signInButton}
size="large"
onPress={handleSubmit}
disabled={isSubmitting}
accessoryRight={() => (isSubmitting ? <Spinner size="tiny" /> : null)}
>
{evaProps => <Text {...evaProps} category="p1" style={{ fontSize: 16, color: 'white' }}>{t('common.continue')}</Text>}
</Button>
</>
);
}}
</Formik>
</View>
</KeyboardAvoidingView>
</Layout>
);
};
ValidateUpload.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func,
}),
route: PropTypes.shape({
params: PropTypes.shape({
password: PropTypes.string,
}),
}),
};
ValidateUpload.defaultProps = {
navigation: null,
route: null,
};
export default ValidateUpload;
|
#importing csv as dataframe
Mecha_data <- read.csv('MechaCar_mpg.csv')
#grabbing dplyr library to work with
library(dplyr)
#linear regression formula
lm(mpg ~ vehicle_length + vehicle_weight + spoiler_angle + ground_clearance + AWD, Mecha_data)
#summary of linear regression
summary(lm(mpg ~ vehicle_length + vehicle_weight + spoiler_angle + ground_clearance + AWD, Mecha_data))
##DELIVERABLE 2
#importing csv as dataframe
SusCoil <- read.csv('Suspension_Coil.csv')
#Make table of Suspension Coil
CoilSummary <- SusCoil %>% summarize(Mean = mean(PSI), Median = median(PSI), Variance = var(PSI), SD = sd(PSI))
#A lot summary of data from table
lot_summary <- SusCoil %>% group_by(Manufacturing_Lot) %>% summarize(Mean = mean(PSI), Median = median(PSI), Variance = var(PSI), SD = sd(PSI))
## DELIVERABLE 3
# T Test for PSI versus population of 1,500 pounds/sq. inch
t.test(SusCoil$PSI, mu=1500)
#T Tests for each lot
t.test(subset(SusCoil,Manufacturing_Lot=="Lot1")$PSI, mu = 1500)
t.test(subset(SusCoil,Manufacturing_Lot=="Lot2")$PSI, mu = 1500)
t.test(subset(SusCoil,Manufacturing_Lot=="Lot3")$PSI, mu = 1500)
|
#pragma once
#include "libraries.h"
/**
* @brief Función que pide al usuario valores del grafo a usar.
* @param &graph `std::vector<std::vector<int>>`
* @param n ´int´ tamaño de grafo
* @note `Time complexity - O(n²)`
* @result Matriz modificada con valores del usuario
*/
void getGraph(int n, std::vector<std::vector<int>> &graph, int itr) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cin >> graph[i][j];
}
}
}
/**
* @brief Función que pide al usuario valores principales.
* @param std::vector<int> `&x` simboliza número
* @note `Time complexity - O(1)`
* @result Número modificado con valor del usuario
*/
void getSizeGraph(int &x, int itr) {
std::cin >> x;
}
/**
* @brief Función que genera mapa de grafos con archivos de prueba.
* @param std::vector<int> `&x` simboliza número
* @note `Time complexity - O(n²)`
* @result `std::map<int, std::vector<std::vector<int>>>`
*/
void readInputTxt(int itr,
std::map<int, std::vector<std::vector<int>>> &graphsMap,
std::vector<std::pair<int, int>> &coords) {
std::string readFile = "Equipo_02_Entrada_" + std::to_string(itr + 1) + ".txt";
std::ifstream inputFile(readFile);
if (!inputFile.is_open()) {
std::cerr << "Error opening the file." << std::endl;
}
int sizeGraph;
int graphs = 0;
inputFile >> sizeGraph;
// Parte de grafos
while(graphs < 2) {
for(int i = 0; i < sizeGraph; i++) {
std::vector<int> row;
for(int j = 0; j < sizeGraph; j++) {
int value;
inputFile >> value;
row.push_back(value);
}
graphsMap[graphs].push_back(row);
}
graphs++;
}
// Parte de coordenadas
while (!inputFile.eof()) {
int x, y;
char openParenthesis, comma, closeParenthesis;
inputFile >> openParenthesis >> x >> comma >> y >> closeParenthesis;
if (inputFile.fail()) {
break;
}
std::pair<int, int> tuple = {x, y};
coords.push_back(tuple);
}
}
/**
* @brief Función que genera grafos apartir del mapa de vectores.
* @param totalGraphs `int`
* @param graphColonies `std::vector<std::vector<int>>`
* @param graphFlow `std::vector<std::vector<int>>`
* @param graphsMap `std::map<int, std::vector<std::vector<int>>>`
* @note `Time complexity - O(n²)`
* @result `Grafos para aplicaciones de algoritmos`
*/
void createGraphs(int totalGraphs,
std::vector<std::vector<int>> &graphColonies,
std::vector<std::vector<int>> &graphFlow,
std::map<int, std::vector<std::vector<int>>> graphsMap) {
for (int x = 0; x < totalGraphs; x++) {
for (int i = 0; i < graphsMap[x].size(); i++) {
for (int j = 0; j < graphsMap[x].size(); j++) {
if (!x) {
graphColonies[i][j] = graphsMap[x][i][j];
}
else {
graphFlow[i][j] = graphsMap[x][i][j];
}
}
}
}
}
|
<!doctype html>
<head>
<title>Hikima - Profile</title>
<link rel="stylesheet" href="{{ url_for('static', filename='bootstrap/css/bootstrap.min.css') }}">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/tailwind.min.css"/>
<!--Replace with your tailwind.css once created-->
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel="stylesheet" />
<!-- Define your gradient here - use online tools to find a gradient matching your branding-->
<style>
.gradient {
background: linear-gradient(90deg, #d53369 0%, #daae51 100%);
}
</style>
</head>
<html>
<body>
<!--Nav-->
<nav id="header" class="d-grid gap-2 d-sm-flex justify-content-sm-center align-items-center my-1">
<div class="w-full container mx-auto flex flex-wrap items-center justify-between mt-0 py-2">
<div class="pl-4 flex items-center">
<a class="toggleColour text-black no-underline hover:no-underline font-bold text-2xl lg:text-4xl" href="">
<!--Icon from: http://www.potlabicons.com/
<svg class="h-8 fill-current inline" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512.005 512.005">
<rect fill="#2a2a31" x="16.539" y="425.626" width="479.767" height="50.502" transform="matrix(1,0,0,1,0,0)" />
</svg>
-->
Hikima
</a>
</div>
<div class="block lg:hidden pr-4">
<button id="nav-toggle" class="flex items-center p-1 text-pink-800 hover:text-gray-900 focus:outline-none focus:shadow-outline transform transition hover:scale-105 duration-300 ease-in-out">
<svg class="fill-current h-6 w-6" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<title>Menu</title>
<path d="M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z" />
</svg>
</button>
</div>
<div class="w-full flex-grow lg:flex lg:items-center lg:w-auto hidden mt-2 lg:mt-0 bg-white lg:bg-transparent text-black p-4 lg:p-0 z-20" id="nav-content">
<ul class="list-reset lg:flex justify-end flex-1 items-center">
<li class="mr-3">
<a class="inline-block text-black no-underline hover:text-gray-800 hover:text-underline py-2 px-4" href="#">Assistant</a>
</li>
<li class="mr-3">
<a class="inline-block py-2 px-4 text-black font-bold no-underline" href="">Speech</a>
</li>
<li class="mr-3">
<a class="inline-block text-black no-underline hover:text-gray-800 hover:text-underline py-2 px-4" href="#">Music</a>
</li>
<li class="mr-3">
<a class="inline-block text-black no-underline hover:text-gray-800 hover:text-underline py-2 px-4" href="#">Translation</a>
</li>
<li class="mr-3">
<a class="inline-block text-black no-underline hover:text-gray-800 hover:text-underline py-2 px-4" href="#">Developer</a>
</li>
<li class="mr-3">
<a class="inline-block text-black no-underline hover:text-gray-800 hover:text-underline py-2 px-4" href="/logout">Sign Out</a>
</li>
</ul>
<!--
<button
id="navAction"
class="mx-auto lg:mx-0 hover:underline bg-white text-gray-800 font-bold rounded-full mt-4 lg:mt-0 py-4 px-8 shadow opacity-75 focus:outline-none focus:shadow-outline transform transition hover:scale-105 duration-300 ease-in-out"
>
Sign In
</button>
-->
</div>
</div>
<hr class="border-b border-gray-100 opacity-25 my-0 py-0" />
</nav>
<main>
<div class="px-4 py-3 my-2 text-center">
<!--
<img src="{{ url_for('static', filename='images/hero.png') }}" alt="Azure Logo" width="400" height="350""/>
-->
<div class="container">
<h1 class="fs-5 title">Click to Start Recording. Read The Sentence Below</h1>
<div class="box">
<p class="fs-5 text-primary subtitle"><br> "<span id="sentence"></span>"</p>
<button class="mx-auto lg:mx-0 hover:underline bg-white text-gray-800 font-bold rounded-full mt-4 lg:mt-0 py-4 px-8 shadow opacity-75 focus:outline-none focus:shadow-outline transform transition hover:scale-105 duration-300 ease-in-out" id="startBtn">Start Recording</button>
<button class="mx-auto lg:mx-0 hover:underline bg-white text-gray-800 font-bold rounded-full mt-4 lg:mt-0 py-4 px-8 shadow opacity-75 focus:outline-none focus:shadow-outline transform transition hover:scale-105 duration-300 ease-in-out" id="stopBtn" disabled>Stop Recording</button>
<button class="mx-auto lg:mx-0 hover:underline bg-white text-gray-800 font-bold rounded-full mt-4 lg:mt-0 py-4 px-8 shadow opacity-75 focus:outline-none focus:shadow-outline transform transition hover:scale-105 duration-300 ease-in-out" id="delBtn" disabled>Delete Recording</button>
</div>
<p class="fs-6">Timer</p>
<div class="d-grid gap-2 d-sm-flex justify-content-sm-center align-items-center my-1">
<progress class="progress-bar" value="0" max="15" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100" id="progressBar"></progress>
</div>
<p class="help">Please allow microphone access to record.</p>
</div>
<div class="d-grid gap-2 d-sm-flex justify-content-sm-center align-items-center my-1">
<p class="fs-5"> </p>
<p class="fs-6 text-primary">© 2023 Hikima Research Lab</p>
<p class="fs-5"> </p>
</div>
</main>
<script>
/*Toggle dropdown list*/
/*https://gist.github.com/slavapas/593e8e50cf4cc16ac972afcbad4f70c8*/
var navMenuDiv = document.getElementById("nav-content");
var navMenu = document.getElementById("nav-toggle");
document.onclick = check;
function check(e) {
var target = (e && e.target) || (event && event.srcElement);
//Nav Menu
if (!checkParent(target, navMenuDiv)) {
// click NOT on the menu
if (checkParent(target, navMenu)) {
// click on the link
if (navMenuDiv.classList.contains("hidden")) {
navMenuDiv.classList.remove("hidden");
} else {
navMenuDiv.classList.add("hidden");
}
} else {
// click both outside link and outside menu, hide menu
navMenuDiv.classList.add("hidden");
}
}
}
function checkParent(t, elm) {
while (t.parentNode) {
if (t == elm) {
return true;
}
t = t.parentNode;
}
return false;
}
// Get references to the elements
const sentenceSpan = document.getElementById('sentence');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const progressBar = document.getElementById('progressBar');
let mediaRecorder;
let audioChunks = [];
// Replace this with your list of sentences to read
const sentences = [
"Bringing technology to your doorstep in an accelarating time.",
"Under whose authority does a machine learning dataset is built?",
"Overfitting is a major problem in training an AI model, in what ways can this be addressed?"
];
let currentIndex = 0;
// Function to update the UI with the current sentence
function updateSentence() {
if (currentIndex < sentences.length) {
sentenceSpan.textContent = sentences[currentIndex];
} else {
sentenceSpan.textContent = "Recording complete!";
}
}
// Function to start recording
function startRecording() {
const constraints = { audio: true };
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = event => {
if (event.data.size > 0) {
audioChunks.push(event.data);
}
};
mediaRecorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const formData = new FormData();
formData.append('user_id', 'user123'); // Replace with the actual user ID
formData.append('sentence', sentences[currentIndex]);
formData.append('audio', audioBlob, 'recording.wav');
// Send the recording data to the server using a fetch request
fetch('/record', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data);
currentIndex++;
audioChunks = [];
updateSentence();
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while saving the recording. Please try again.');
});
};
mediaRecorder.start();
startBtn.disabled = true;
stopBtn.disabled = false;
progressBar.value = 0;
const timer = setInterval(() => {
progressBar.value++;
if (progressBar.value === progressBar.max) {
clearInterval(timer);
mediaRecorder.stop();
startBtn.disabled = false;
stopBtn.disabled = true;
}
}, 1000);
})
.catch(error => {
console.error('Error:', error);
alert('Failed to access the microphone. Please make sure you have granted microphone access.');
});
}
// Event listeners for the buttons
startBtn.addEventListener('click', startRecording);
stopBtn.addEventListener('click', () => {
mediaRecorder.stop();
startBtn.disabled = false;
stopBtn.disabled = true;
progressBar.value = 0;
});
// Initial update of the UI
updateSentence();
</script>
</body>
</html>
|
import {apiPlayerActionToPlayerAction, tableArrayToView} from "./mappers";
import {Announce} from "tarot-game-engine";
import {Table} from "../games/table";
import {MockedTarotPlayerAtTable} from "../games/__mock__/mocked-tarot-player-at-table";
describe(`Mapper`, () => {
test(`Given an announce api player action with a known announce,
when converting to player action,
then return expected player action`, () => {
expect(apiPlayerActionToPlayerAction({
action: "ANNOUNCE",
announce: "GARDE"
})).toEqual({
action: "ANNOUNCE",
announce: Announce.GARDE
})
});
test(`Given an announce api player action with no announce,
when converting to player action,
then return expected player action`, () => {
expect(apiPlayerActionToPlayerAction({
action: "ANNOUNCE",
announce: "NOTHING"
})).toEqual({
action: "ANNOUNCE",
announce: undefined
})
});
test(`Given a play api player action with no announce,
when converting to player action,
then return expected player action`, () => {
expect(apiPlayerActionToPlayerAction({
action: "PLAY",
card: "T1"
})).toEqual({
action: "PLAY",
card: "T1"
})
});
test(`Given an array of tables with one table on which one player has joined,
when converting to all table views,
then return expected result`, () => {
const tableId = "TABLE_ID"
const tableName = "TABLE_NAME"
const playerId = "PLAYER_ID"
const playerName = "PLAYER_NAME";
const aPlayer = new MockedTarotPlayerAtTable(playerId, playerName);
const table = new Table(tableId, tableName, jest.fn())
table.join(aPlayer);
expect(tableArrayToView([table]))
.toEqual([{
id: tableId,
name: tableName,
players: [
{
id: playerId,
name: playerName
}
],
maxNumberOfPlayers: 4,
numberOfPlayers: 1
}])
});
})
|
import "animate.css/animate.min.css";
import "rc-slider/assets/index.css";
import * as React from "react";
import ScrollAnimation from "react-animate-on-scroll";
import withTheme, { InjectedThemeProps } from "../../theme/withTheme";
import featureBlockStyle from "./FeatureBlockStyle";
interface State {
}
export interface Props extends InjectedThemeProps {
icon: any;
title: string;
description: string;
}
class FeatureBlock extends React.Component<Props, State> {
public render(): any {
const { theme, icon, title, description } = this.props;
const style = featureBlockStyle(theme);
return (
<div className={style.mainContainer} >
<ScrollAnimation animateIn="zoomIn" duration={0.3} animateOnce={true} ><div className={style.icon} ><img src={icon} /></div></ScrollAnimation>
<div className={style.title} dangerouslySetInnerHTML={{__html: title}} />
<div className={style.description} dangerouslySetInnerHTML={{__html: description}} />
</div>
);
}
}
export default withTheme(FeatureBlock);
|
import ForgotPasswordEmailForm from "@/components/authComponents/ForgotPasswordEmailForm";
import ForgotPasswordOtpTokenForm from "@/components/authComponents/ForgotPasswordOtpTokenForm";
import ForgotPasswordSetPasswordForm from "@/components/authComponents/ForgotPasswordSetPasswordForm";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useState } from "react";
export interface StateType {
email: string;
newPassword: string;
forgotPasswordOtp: string;
}
function ForgotPasswordRoute() {
const [state, setState] = useState<StateType>({
email: "",
newPassword: "",
forgotPasswordOtp: "",
});
return (
<ScrollArea className="w-full">
<main className="flex-1 flex justify-center px-4 pt-12 pb-8">
{state.email === "" && <ForgotPasswordEmailForm setState={setState} />}
{state.email && state.newPassword === "" && (
<ForgotPasswordSetPasswordForm setState={setState} state={state} />
)}
{state.email && state.newPassword && (
<ForgotPasswordOtpTokenForm state={state} />
)}
</main>
</ScrollArea>
);
}
export default ForgotPasswordRoute;
|
import pandas as pd
import numpy as np
import random as rnd
import os
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier
input_folder = os.getcwd() + "/titanic_machine_learning_from_disaster/datasets/"
output_folder = os.getcwd() + "/titanic_machine_learning_from_disaster/output/"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
train_df = pd.read_csv(os.path.join(input_folder, 'train.csv'))
test_df = pd.read_csv(os.path.join(input_folder, 'test.csv'))
combine = [train_df, test_df]
print("Pivot points by ticket class \n" + train_df[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False).mean().sort_values(by='Survived', ascending=False).to_string())
print("Pivot points by sex \n" + train_df[['Sex', 'Survived']].groupby(['Sex'], as_index=False).mean().sort_values(by='Survived', ascending=False).to_string())
g = sns.FacetGrid(train_df, col='Survived')
g.map(plt.hist, 'Age', bins=20)
#plt.show()
g.savefig(os.path.join(output_folder, 'grid_age_survival.png'))
order = train_df['Pclass'].sort_values().unique()
hue_order = train_df['Sex'].sort_values().unique()
grid = sns.FacetGrid(train_df, row='Embarked', height=2.2, aspect=1.6)
grid.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', palette='deep', order=order, hue_order=hue_order)
grid.add_legend()
#plt.show()
grid.savefig(os.path.join(output_folder, 'grid_embarked_class_sex_survival.png'))
# drop the "Cabin" and "Ticket" features.
print("Before", train_df.shape, test_df.shape, combine[0].shape, combine[1].shape)
train_df = train_df.drop(['Ticket', 'Cabin'], axis=1)
test_df = test_df.drop(['Ticket', 'Cabin'], axis=1)
combine = [train_df, test_df]
print("After", train_df.shape, test_df.shape, combine[0].shape, combine[1].shape)
# Extract titles from the "Name" feature.
for dataset in combine:
dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False)
print("title-sex table \n " +pd.crosstab(train_df['Title'], train_df['Sex']).to_string())
# Replace many titles with a more common name or classify them as "Rare".
for dataset in combine:
dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess', 'Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')
dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')
dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')
print("title-survival table \n" + train_df[['Title', 'Survived']].groupby(['Title'], as_index=False).mean().to_string())
# Convert the categorical titles to ordinal.
title_mapping = {'Mr': 1, 'Miss': 2, 'Mrs': 3, 'Master': 4, 'Rare': 5}
for dataset in combine:
dataset['Title'] = dataset['Title'].map(title_mapping)
dataset['Title'] = dataset['Title'].fillna(0)
print("After title conversion \n" + train_df.head().to_string())
# Drop the "Name" and "PassengerId" features.
train_df = train_df.drop(['Name', 'PassengerId'], axis=1)
test_df = test_df.drop(['Name'], axis=1)
combine = [train_df, test_df]
print("After dropping Name and PassengerId \n" + train_df.head().to_string())
# Convert sex to the categorical features
for dataset in combine:
dataset['Sex'] = dataset['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
print("After sex to the categorical features \n" + train_df.head().to_string())
# Completing a numerical continuous feature
grid = sns.FacetGrid(train_df, row='Pclass', col='Sex', height=2.2, aspect=1.6)
grid.map(plt.hist, 'Age', alpha=.5, bins=20)
grid.add_legend()
#plt.show()
grid.savefig(os.path.join(output_folder, 'grid_age_class_sex.png'))
guess_ages = np.zeros((2,3))
for dataset in combine:
for i in range(0, 2):
for j in range(0, 3):
guess_df = dataset[(dataset['Sex'] == i) & (dataset['Pclass'] == j+1)]['Age'].dropna()
age_guess = guess_df.median()
guess_ages[i,j] = int( age_guess/0.5 + 0.5 ) * 0.5
for i in range(0, 2):
for j in range(0, 3):
dataset.loc[ (dataset.Age.isnull()) & (dataset.Sex == i) & (dataset.Pclass == j+1),\
'Age'] = guess_ages[i,j]
dataset['Age'] = dataset['Age'].astype(int)
# train_df['AgeBand'] = pd.cut(train_df['Age'], 5)
# train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False).mean().sort_values(by='AgeBand', ascending=True)
# AgeBand Survived
# 0 (-0.08, 16.0] 0.550000
# 1 (16.0, 32.0] 0.337374
# 2 (32.0, 48.0] 0.412037
# 3 (48.0, 64.0] 0.434783
# 4 (64.0, 80.0] 0.090909
print("calculated guessed values of Age for the six combinations. \n" + train_df.head().to_string())
for dataset in combine:
dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0
dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 32), 'Age'] = 1
dataset.loc[(dataset['Age'] > 32) & (dataset['Age'] <= 48), 'Age'] = 2
dataset.loc[(dataset['Age'] > 48) & (dataset['Age'] <= 64), 'Age'] = 3
dataset.loc[ dataset['Age'] > 64, 'Age']
print("After converting Age to categorical \n" + train_df.head().to_string())
# Is surviver single or married
for dataset in combine:
dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1
for dataset in combine:
dataset['IsAlone'] = 0
dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1
print("Is surviver is alone \n" + train_df[['IsAlone', 'Survived']].groupby(['IsAlone'], as_index=False).mean().to_string())
train_df = train_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)
test_df = test_df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)
combine = [train_df, test_df]
for dataset in combine:
dataset['Age*Class'] = dataset.Age * dataset.Pclass
freq_port = train_df.Embarked.dropna().mode()[0]
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)
print("Embarked to categorical \n" + train_df[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False).mean().sort_values(by='Survived', ascending=False).to_string())
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)
test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)
train_df['FareBand'] = pd.qcut(train_df['Fare'], 4)
for dataset in combine:
dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0
dataset.loc[(dataset['Fare'] > 7.91) & (dataset['Fare'] <= 14.454), 'Fare'] = 1
dataset.loc[(dataset['Fare'] > 14.454) & (dataset['Fare'] <= 31), 'Fare'] = 2
dataset.loc[ dataset['Fare'] > 31, 'Fare'] = 3
dataset['Fare'] = dataset['Fare'].astype(int)
train_df = train_df.drop(['FareBand'], axis=1)
combine = [train_df, test_df]
print("After converting Fare to categorical \n" + train_df.head().to_string())
X_train = train_df.drop("Survived", axis=1)
Y_train = train_df["Survived"]
X_test = test_df.drop("PassengerId", axis=1).copy()
logreg = LogisticRegression()
logreg.fit(X_train, Y_train)
Y_pred = logreg.predict(X_test)
acc_log = round(logreg.score(X_train, Y_train) * 100, 2)
print("Logistic Regression accuracy \n" + str(acc_log))
coeff_df = pd.DataFrame(train_df.columns.delete(0))
coeff_df.columns = ['Feature']
coeff_df["Correlation"] = pd.Series(logreg.coef_[0])
print("Correlation between features and survival \n" + coeff_df.sort_values(by='Correlation', ascending=False).to_string())
svc = SVC()
svc.fit(X_train, Y_train)
Y_pred = svc.predict(X_test)
acc_svc = round(svc.score(X_train, Y_train) * 100, 2)
print("Support Vector Machines accuracy \n" + str(acc_svc))
knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X_train, Y_train)
Y_pred = knn.predict(X_test)
acc_knn = round(knn.score(X_train, Y_train) * 100, 2)
print("KNN accuracy \n" + str(acc_knn))
gaussian = GaussianNB()
gaussian.fit(X_train, Y_train)
Y_pred = gaussian.predict(X_test)
acc_gaussian = round(gaussian.score(X_train, Y_train) * 100, 2)
print("Gaussian Naive Bayes accuracy \n" + str(acc_gaussian))
decision_tree = DecisionTreeClassifier()
decision_tree.fit(X_train, Y_train)
Y_pred = decision_tree.predict(X_test)
acc_decision_tree = round(decision_tree.score(X_train, Y_train) * 100, 2)
print("Decision Tree accuracy \n" + str(acc_decision_tree))
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, Y_train)
Y_pred = random_forest.predict(X_test)
random_forest.score(X_train, Y_train)
acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
print("Random Forest accuracy \n" + str(acc_random_forest))
models = pd.DataFrame({
'Model': ['Support Vector Machines', 'KNN', 'Logistic Regression',
'Random Forest', 'Naive Bayes',
'Decision Tree'],
'Score': [acc_svc, acc_knn, acc_log,
acc_random_forest, acc_gaussian, acc_decision_tree]})
models.sort_values(by='Score', ascending=False)
submission = pd.DataFrame({
"PassengerId": test_df["PassengerId"],
"Survived": Y_pred
})
submission.to_csv(os.path.join(output_folder, 'submission.csv'), index=False)
|
//
// ManualCodeGenerator.swift
// Walletsmith
//
// Created by Juan Rodríguez on 10/1/23.
//
import SwiftUI
struct ManualCodeGenerator: View {
@Environment(\.colorScheme) var colorScheme
let dismissNavigationView: DismissAction?
var completion: (Barcode) -> Void
@StateObject var barcode = Barcode(.QR, text: "Hi!", persist: false)
@State private var selectedFormat: Barcode.Format = .QR
@State private var barcodeImageId: Int = 0
init(dismissNavigationView: DismissAction? = nil, completion: @escaping (Barcode) -> Void) {
self.dismissNavigationView = dismissNavigationView
self.completion = completion
}
var body: some View {
List {
Section {
HStack {
Spacer()
VStack {
VStack {
Spacer()
Image(uiImage: barcode.image)
.resizable()
.aspectRatio(contentMode: .fit)
.id(barcodeImageId)
Spacer()
}
.onChange(of: selectedFormat) { newValue in
Task {
barcode.typedFormat = newValue
await barcode.generateImage()
barcodeImageId += 1
}
}
Spacer()
Button {
completion(barcode)
dismissNavigationView?()
} label: {
HStack {
Spacer()
Text("Add to pass")
.bold()
.foregroundColor(colorScheme == .dark ? .black : .white)
Spacer()
}
.frame(height: 25)
}
.buttonStyle(.borderedProminent)
.controlSize(.large)
}
.frame(height: 300)
Spacer()
}
}
Section("Format") {
Picker(selection: $selectedFormat) {
Text(Barcode.readableFormat(.QR)).tag(Barcode.Format.QR)
Text(Barcode.readableFormat(.AZTEC)).tag(Barcode.Format.AZTEC)
Text(Barcode.readableFormat(.PDF417)).tag(Barcode.Format.PDF417)
Text(Barcode.readableFormat(.Code128)).tag(Barcode.Format.Code128)
#if DEBUG
Text(Barcode.Format.DATAMATRIX.rawValue).tag(Barcode.Format.DATAMATRIX)
#endif
} label: {
Text("Format")
}
}
Section("Payload") {
TextEditor(text: $barcode.message)
.submitLabel(.done)
}
}
.navigationTitle(Text("Code editor"))
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Cancel") {
dismissNavigationView?()
}
}
}
.onChange(of: barcode.format) { _ in
Task {
await barcode.generateImage()
barcodeImageId += 1
}
}
.onChange(of: barcode.message) { _ in
Task {
await barcode.generateImage()
barcodeImageId += 1
}
}
.task {
await barcode.generateImage()
barcodeImageId += 1
}
}
}
struct ManualCodeGenerator_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ManualCodeGenerator { _ in
}
}
}
}
|
import { useContext } from "react"
import "./checkout.css"
import { AuthContext } from "../../contexts/AuthContext"
import { useForm } from "../../hooks/useForm"
const customerFromKeys = {
Email: 'email',
Name: 'name',
CreditCard: {
Name: 'name',
CardNumber: 'cardNumber',
ExpirationYear: 'expirationYear',
ExpirationMonth: 'expirationMonth',
Cvc: 'cvc'
}
}
export const Checkout = () => {
const { addStripeCustomer } = useContext(AuthContext);
const { values, changeHandler, onSubmit} = useForm(
{
[customerFromKeys.Email]: '',
[customerFromKeys.Name]: '',
[customerFromKeys.CreditCard.Name]: '',
[customerFromKeys.CreditCard.CardNumber]: '',
[customerFromKeys.CreditCard.ExpirationYear]: '',
[customerFromKeys.CreditCard.ExpirationMonth]: '',
[customerFromKeys.CreditCard.Cvc]: ''
}, addStripeCustomer
)
return (
<section>
<div className="row">
<div className="col-75">
<div className="container cont">
<form id="checkout" onSubmit={onSubmit} method="POST">
<div className="row">
<div className="col-50">
<h3>Billing Address</h3>
<label htmlFor="fname">
<i className="fa fa-user"></i> Full Name
</label>
<input
type="text"
id="fname"
name={customerFromKeys.Name}
value={values[customerFromKeys.Name]}
placeholder="John M. Doe"
onChange={changeHandler}
/>
<label htmlFor="email">
<i className="fa fa-envelope"></i> Email
</label>
<input
type="text"
id="email"
name={customerFromKeys.Email}
placeholder="[email protected]"
value={values[customerFromKeys.Email]}
onChange={changeHandler}
/>
<label htmlFor="adr">
<i className="fa fa-address-card-o"></i> Address
</label>
<input
type="text"
id="adr"
name="address"
placeholder="542 W. 15th Street"
/>
<label htmlFor="city">
<i className="fa fa-institution"></i> City
</label>
<input
type="text"
id="city"
name="city"
placeholder="New York"
/>
<div className="row">
<div className="col-50">
<label htmlFor="state">State</label>
<input
type="text"
id="state"
name="state"
placeholder="NY"
/>
</div>
<div className="col-50">
<label htmlFor="zip">Zip</label>
<input
type="text"
id="zip"
name="zip"
placeholder="10001"
/>
</div>
</div>
</div>
<div className="col-50">
<h3>Payment</h3>
<label htmlFor="fname">Accepted Cards</label>
<div className="icon-container">
<i className="fa fa-cc-visa"></i>
<i className="fa fa-cc-amex" ></i>
<i className="fa fa-cc-mastercard" ></i>
<i className="fa fa-cc-discover" ></i>
</div>
<label htmlFor="cname">Name on Card</label>
<input
type="text"
id="cname"
name={customerFromKeys.CreditCard.Name}
placeholder="John More Doe"
value={values[customerFromKeys.CreditCard.Name]}
onChange={changeHandler}
/>
<label htmlFor="ccnum">Credit card number</label>
<input
type="text"
id="ccnum"
name={customerFromKeys.CreditCard.CardNumber}
placeholder="1111-2222-3333-4444"
value={values[customerFromKeys.CreditCard.CardNumber]}
onChange={changeHandler}
/>
<label htmlFor="expmonth">Exp Month</label>
<input
type="text"
id="expmonth"
name={customerFromKeys.CreditCard.ExpirationMonth}
placeholder="September"
value={values[customerFromKeys.CreditCard.ExpirationMonth]}
onChange={changeHandler}
/>
<div className="row">
<div className="col-50">
<label htmlFor="expyear">Exp Year</label>
<input
type="text"
id="expyear"
name={customerFromKeys.CreditCard.ExpirationYear}
placeholder="2018"
value={values[customerFromKeys.CreditCard.ExpirationYear]}
onChange={changeHandler}
/>
</div>
<div className="col-50">
<label htmlFor="cvv">CVV</label>
<input
type="text"
id="cvv"
name={customerFromKeys.CreditCard.Cvc}
placeholder="352"
value={values[customerFromKeys.CreditCard.Cvc]}
onChange={changeHandler}
/>
</div>
</div>
</div>
</div>
<label>
<input type="checkbox" name="sameadr">
</input>
</label>
<input type="submit" value="Continue to checkout" className="btnCheck " />
</form>
</div>
</div>
</div>
</section>
);
}
|
import { environment } from '../../environments/environment';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Employer } from '../model/Employer';
@Injectable({providedIn: 'root'})
export class EmployerService {
private URI = 'employers';
constructor(private httpClient: HttpClient) { }
public getEmployers(): Observable<any> {
return this.httpClient.get<any>(`${environment.API}/${this.URI}`);
}
public getEmployersPageable(page: number, rows: number): Observable<any> {
return this.httpClient.get<any>(`${environment.API}/${this.URI}/employers-pageable?page=${page}&rows=${rows}`);
}
public findEmployers(query: string): Observable<Employer[]> {
return this.httpClient.get<Employer[]>(`${environment.API}/${this.URI}/find?query=${query}`);
}
public emailAlreadyRegistered(query: string): Observable<boolean> {
return this.httpClient.get<boolean>(`${environment.API}/${this.URI}/email-already-registered?query=${query}`);
}
public getEmployer(id: string): Observable<Employer> {
return this.httpClient.get<Employer>(`${environment.API}/${this.URI}/${id}`);
}
public create(employer: any): Observable<any> {
return this.httpClient.post<any>(`${environment.API}/${this.URI}`, employer);
}
public update(employer: any): Observable<Employer> {
return this.httpClient.put<Employer>(`${environment.API}/${this.URI}`, employer);
}
public delete(id: string): Observable<any> {
return this.httpClient.delete<any>(`${environment.API}/${this.URI}/${id}`);
}
}
|
"Use Strict";
var Promise = require("bluebird");
var assert = require('assert');
var proxyquire = require('proxyquire').noCallThru();
var manager = require('../../Managers/RunthroughManager.js');
var blank = undefined;
describe('Runthrough Manager', function () {
var fakeDatabase = {};
var fakeManager = proxyquire('../../Managers/RunthroughManager.js', {
'../Database': fakeDatabase,
'../Managers/StoryManager': {
Get: function (item) {
return Promise.resolve({});
}
}
});
describe('Public functions:', function(){
it('Get != undefined', function(){
assert.notEqual(manager.Get, undefined);
})
})
describe('Get:', function(){
var valid = 1;
var invalid = 0;
var invalidFormat = 'invalid';
it('Valid:', function(done){
var validRow = {"ID":1,"Name":"Test","Description":"Test","Speed":10,"Size":1,"Version":1};
fakeDatabase.Procedure = function (procedure, values, callback) {
assert.equal(procedure, 'sp_GetRunthroughByID');
assert.equal(values.length, 1);
assert.equal(values[0], valid);
assert.notEqual(callback, undefined);
callback([validRow]);
};
fakeManager.Get(valid).then(function(result){
assert.notEqual(result, undefined);
assert.equal(result.Reason, undefined);
assert.notEqual(result.ID, undefined);
assert.notEqual(result.Story, undefined);
done();
},
function(error){
done(new Error(JSON.stringify(error)));
});
})
it('Invalid "ID" Value:', function(done){
fakeDatabase.Procedure = function (procedure, values, callback) {
assert.equal(procedure, 'sp_GetRunthroughByID');
assert.equal(values.length, 1);
assert.equal(values[0], invalid);
assert.notEqual(callback, undefined);
callback([]);
};
fakeManager.Get(invalid).then(function(error){
done(new Error(JSON.stringify(error)));
},
function(result){
assert.notEqual(result, undefined);
assert.notEqual(result.Reason, undefined);
assert.equal(result.ID, undefined);
assert.equal(result.Story, undefined);
done();
});
})
it('Invalid "ID" Format:', function(done){
fakeDatabase.Procedure = function (procedure, values, callback) {
assert.equal(procedure, 'sp_GetRunthroughByID');
assert.equal(values.length, 1);
assert.equal(values[0], invalidFormat);
assert.notEqual(callback, undefined);
callback([]);
};
fakeManager.Get(invalidFormat).then(function(error){
done(new Error(JSON.stringify(error)));
},
function(result){
assert.notEqual(result, undefined);
assert.notEqual(result.Reason, undefined);
assert.equal(result.ID, undefined);
assert.equal(result.Story, undefined);
done();
});
})
it('Missing "ID":', function(done){
fakeDatabase.Procedure = function (procedure, values, callback) {
assert.equal(procedure, 'sp_GetRunthroughByID');
assert.equal(values.length, 1);
assert.equal(values[0], blank);
assert.notEqual(callback, undefined);
callback([]);
};
fakeManager.Get(blank).then(function(error){
done(new Error(JSON.stringify(error)));
},
function(result){
assert.notEqual(result, undefined);
assert.notEqual(result.Reason, undefined);
assert.equal(result.ID, undefined);
assert.equal(result.Story, undefined);
done();
});
})
});
});
|
<template>
<div class="registration-form">
<Form ref="userForm" :model="userModel" :rules="validateUserRules">
<div class="registration-form-group">
<h3 class="registration-form-group__title">
{{ $tr('registration.profileTitle') }}
</h3>
<div class="row">
<FormItem
:label="$tr('registration.email')"
class="col-12 col-md-6 col-lg-4"
prop="email"
>
<Input v-model="userModel.email" disabled />
</FormItem>
<FormItem
:label="$tr('registration.passwordTitle')"
class="col-12 col-md-6 col-lg-4"
prop="password"
>
<Input
v-model="userModel.password"
:placeholder="$tr('registration.passwordPh')"
type="password"
/>
</FormItem>
<FormItem
:label="$tr('registration.repeatPasswordTitle')"
class="col-12 col-md-6 col-lg-4"
prop="passwordRepeat"
>
<Input
v-model="userModel.passwordRepeat"
:placeholder="$tr('registration.passwordPh')"
type="password"
/>
</FormItem>
</div>
</div>
</Form>
</div>
</template>
<script>
export default {
model: {
prop: 'form',
event: 'updateFormModel',
},
props: {
form: { type: Object, default: () => ({}) },
eventData: { type: Object, default: () => ({}) },
},
data() {
const repeatEqual = (rule, value, cb) => {
if (value !== this.userModel.password) {
cb(new Error(this.$tr('registration.repeatEqual')))
} else {
cb()
}
}
return {
userModel: {
...this.form,
isValid: false,
},
validateUserRules: {
email: [{ required: true, message: this.$tr('initValidation.required'), trigger: 'blur' }],
password: [
{ required: true, message: this.$tr('initValidation.required'), trigger: 'blur' },
{ min: 6, message: this.$tr('auth.password.errorLength') },
{ max: 255, message: this.$tr('auth.password.errorLengthMax') },
],
passwordRepeat: [
{ required: true, message: this.$tr('initValidation.required'), trigger: 'blur' },
{ validator: repeatEqual, trigger: 'blur' },
],
},
}
},
watch: {
userModel: {
async handler(value) {
if (!this.$refs.userForm) {
return
}
const isValid = await this.$refs.userForm.validate()
this.$emit('updateFormModel', {
...value,
isValid,
})
},
immediate: true,
deep: true,
},
},
}
</script>
<style lang="scss">
@import '~@/styles/blocks/registration.scss';
</style>
|
<!doctype html>
<html lang="<?php echo e(str_replace('_', '-', app()->getLocale())); ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<title><?php echo e(config('app.name', 'Laravel')); ?></title>
<!-- Scripts -->
<script src="<?php echo e(asset('js/app.js')); ?>" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<!-- Styles -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="<?php echo e(asset('css/main.css')); ?>">
</head>
<body>
<div id="app">
<header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
<a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" href="<?php echo e(url('/')); ?>">
<?php echo e(config('app.name', 'Laravel')); ?>
</a>
<button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse"
data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<div class="navbar-nav">
<!-- Right Side Of Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Authentication Links -->
<?php if(auth()->guard()->guest()): ?>
<?php if(Route::has('login')): ?>
<li class="nav-item">
<a class="nav-link" href="<?php echo e(route('login')); ?>"><?php echo e(__('Login')); ?></a>
</li>
<?php endif; ?>
<?php if(Route::has('register')): ?>
<li class="nav-item">
<a class="nav-link" href="<?php echo e(route('register')); ?>"><?php echo e(__('Register')); ?></a>
</li>
<?php endif; ?>
<?php else: ?>
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
<?php echo e(Auth::user()->name); ?>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="<?php echo e(route('logout')); ?>"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
<?php echo e(__('Logout')); ?>
</a>
<form id="logout-form" action="<?php echo e(route('logout')); ?>" method="POST" class="d-none">
<?php echo csrf_field(); ?>
</form>
</div>
</li>
<?php endif; ?>
</ul>
</div>
</header>
<div class="container-fluid">
<div class="row">
<?php if(auth()->guard()->check()): ?>
<?php echo $__env->make('sidebar.left', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php endif; ?>
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<?php echo $__env->yieldContent('content'); ?>
</main>
</div>
</div>
</div>
</body>
</html>
<?php /**PATH D:\LaravellProjects\todo\resources\views/layouts/app.blade.php ENDPATH**/ ?>
|
import { type } from "@testing-library/user-event/dist/type";
import React from "react";
import "./App.css";
function App() {
let 이름: string = "kim";
let 이름들: string[] = ["kim", "lee", "Part"];
let 복합: string | number = 123;
function 함수(num: number): number {
return num * 2;
}
함수(1);
type Name = string | number;
type Member = [number, boolean];
let john: Member = [123, true];
// 오브젝트 타입 지정
type Members = {
name: string;
};
let sean: Members = { name: "kim" };
//오브젝트에 여러 타입 넣기
let 회원들: { member1: string; member2: number } = { member1: "kim", member2: 2 };
//타입스크립트 지정 안해서 자동으로 넣어줌
let 문자면 = "park";
// 싸잡아서 타입 지정
type Members2 = {
[key: string]: string;
};
let grace: Members2 = { name: "kim" };
//클래스 타입 지정
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}
//숫자 문자 다 들어오는 타입 Union 타입 할당 해서버리면 하나로 확정됨
let 회원쓰: number | string | boolean = 123;
// 숫자 또는 문자가 가는한 Array, object
let 사람들: (number | string)[] = [1, "2", 3];
let 오브줵트: { a: string | number } = { a: 123 };
let 애니: any; // 타입 실드 해제 문법임
애니 = 123;
애니 = true;
let 하하: unknown; //최신에 아무거나 집어 넣게 쓰는 것 조금 더 안전함
//하하 - 1; 이런거 안됨 하하가 unknown 타입이라서 빼기 같은게 안됨
//let 나이: string | number;
//나이 + 1; 이런것도 안됨 union 타입에는 안됨
return (
<div className="App">
{이름}
<div>{이름들}</div>
<div>{복합}</div>
</div>
);
}
export default App;
|
import { proto } from '@whiskeysockets/baileys';
import union from 'lodash.union';
import RoleModel from '../../models/Role';
import { ResolverFunction, ResolverFunctionCarry, ResolverResult } from '../../types/resolver';
export const assignUserToRole: ResolverFunctionCarry =
(matches: RegExpMatchArray): ResolverFunction =>
async (message: proto.IWebMessageInfo, jid: string, isFromGroup: Boolean): Promise<ResolverResult> => {
if (!isFromGroup) {
return {
destinationId: jid,
message: { text: 'You can only use role features inside group chat' },
options: {
quoted: message,
},
};
}
const participants = matches[1].trim();
const roleName = matches[2].replace(/[ @]*/g, '');
const role = await RoleModel.findOne({
name: roleName,
groupId: jid,
}).exec();
if (!role) {
return {
destinationId: jid,
message: { text: 'Role not found' },
options: {
quoted: message,
},
};
}
if (participants.indexOf('@everyone') !== -1) {
return {
destinationId: jid,
message: { text: "You can't use @everyone for this command" },
options: {
quoted: message,
},
};
}
let newJids: Array<string> = [];
if (participants.indexOf('@me') !== -1) {
message.key.participant && newJids.push(message.key.participant);
}
newJids = union(newJids, message.message?.extendedTextMessage?.contextInfo?.mentionedJid ?? [], role.participants);
if (!newJids.length) {
return {
destinationId: jid,
message: { text: "There's no users can be assigned to the role" },
options: {
quoted: message,
},
};
}
role.participants = newJids;
await role.save();
return {
destinationId: jid,
message: { text: 'Success' },
options: {
quoted: message,
},
};
};
|
import {
ChatInputCommandInteraction,
Client,
Events,
REST as DiscordRestClient,
Routes,
} from "discord.js";
import { inject, injectable } from "inversify";
import { CommandsHandler } from "../handlers/command";
import { TYPES } from "../types";
import { Logger } from "../utils";
@injectable()
export class MusicBot {
private logger: Logger;
private discordClient: Client;
private discordRestClient: DiscordRestClient;
private commandsHandler: CommandsHandler;
constructor(
@inject(TYPES.Logger) logger: Logger,
@inject(TYPES.DiscordClient) discordClient: Client,
@inject(TYPES.CommandsHandler) commandsHandler: CommandsHandler
) {
this.logger = logger;
this.discordClient = discordClient;
this.commandsHandler = commandsHandler;
this.discordRestClient = new DiscordRestClient().setToken(
process.env.TOKEN
);
}
public async start(): Promise<void> {
try {
this.addClientEventHandlers();
const commands = this.commandsHandler.getSlashCommands();
this.discordClient.login(process.env.DISCORD_ACCESS_TOKEN);
const guilds = await this.discordClient.guilds.fetch();
guilds.forEach((guild) => {
this.discordRestClient
.put(
Routes.applicationGuildCommands(process.env.CLIENT_ID, guild.id),
{ body: commands }
)
.then((data: any) => {
this.logger.info(
`Successfully reloaded ${data.length} application (/) commands to the ${guild.name} server`
);
})
.catch((err) => {
this.logger.error(err);
});
});
} catch (err) {
return Promise.reject(err);
}
}
public async destroy() {
this.discordClient.destroy();
}
addClientEventHandlers() {
this.discordClient.on(Events.InteractionCreate, (interaction) => {
this.commandsHandler
.handleInteraction(interaction as ChatInputCommandInteraction)
.catch((err) => this.logger.error(err));
});
this.discordClient.on(Events.ClientReady, () => {
this.logger.info("Overseer music bot client logged in");
});
this.discordClient.on(Events.ShardReconnecting, () => {
this.logger.info("Overseer music bot client reconnecting");
});
this.discordClient.on(Events.ShardDisconnect, () => {
this.logger.info("Overseer music bot disconnect");
});
}
}
|
/*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package org.nabucco.framework.setup.impl.service.sysvar;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import org.nabucco.framework.base.facade.exception.service.SearchException;
import org.nabucco.framework.base.facade.message.EmptyServiceMessage;
import org.nabucco.framework.base.facade.message.ServiceRequest;
import org.nabucco.framework.base.facade.message.ServiceResponse;
import org.nabucco.framework.base.facade.message.setup.sysvar.SystemVariableMsg;
import org.nabucco.framework.base.facade.service.injection.InjectionException;
import org.nabucco.framework.base.facade.service.injection.InjectionProvider;
import org.nabucco.framework.base.impl.service.ServiceSupport;
import org.nabucco.framework.base.impl.service.maintain.PersistenceManager;
import org.nabucco.framework.base.impl.service.maintain.PersistenceManagerFactory;
import org.nabucco.framework.setup.facade.service.sysvar.SystemVariableService;
/**
* SystemVariableServiceImpl<p/>Service managing system variables.<p/>
*
* @version 1.0
* @author Frank Ratschinski, PRODYNA AG, 2011-04-07
*/
public class SystemVariableServiceImpl extends ServiceSupport implements SystemVariableService {
private static final long serialVersionUID = 1L;
private static final String ID = "SystemVariableService";
private static Map<String, String[]> ASPECTS;
private GetSystemVariablesServiceHandler getSystemVariablesServiceHandler;
private EntityManager entityManager;
/** Constructs a new SystemVariableServiceImpl instance. */
public SystemVariableServiceImpl() {
super();
}
@Override
public void postConstruct() {
super.postConstruct();
InjectionProvider injector = InjectionProvider.getInstance(ID);
PersistenceManager persistenceManager = PersistenceManagerFactory.getInstance().createPersistenceManager(
this.entityManager, super.getLogger());
this.getSystemVariablesServiceHandler = injector.inject(GetSystemVariablesServiceHandler.getId());
if ((this.getSystemVariablesServiceHandler != null)) {
this.getSystemVariablesServiceHandler.setPersistenceManager(persistenceManager);
this.getSystemVariablesServiceHandler.setLogger(super.getLogger());
}
}
@Override
public void preDestroy() {
super.preDestroy();
}
@Override
public String[] getAspects(String operationName) {
if ((ASPECTS == null)) {
ASPECTS = new HashMap<String, String[]>();
ASPECTS.put("getSystemVariables", NO_ASPECTS);
}
String[] aspects = ASPECTS.get(operationName);
if ((aspects == null)) {
return ServiceSupport.NO_ASPECTS;
}
return Arrays.copyOf(aspects, aspects.length);
}
@Override
public ServiceResponse<SystemVariableMsg> getSystemVariables(ServiceRequest<EmptyServiceMessage> rq)
throws SearchException {
if ((this.getSystemVariablesServiceHandler == null)) {
super.getLogger().error("No service implementation configured for getSystemVariables().");
throw new InjectionException("No service implementation configured for getSystemVariables().");
}
ServiceResponse<SystemVariableMsg> rs;
this.getSystemVariablesServiceHandler.init();
rs = this.getSystemVariablesServiceHandler.invoke(rq);
this.getSystemVariablesServiceHandler.finish();
return rs;
}
}
|
// Asynchronous timeout function. Returns a Promise, which throws an Error
// with the given |message| if |ms| milliseconds passes. Also returns a
// timeout id, can be used to cancel the timeout.
export function createAsyncTimeout<T>(message: string, ms: number): [Promise<T>, NodeJS.Timeout] {
let timeoutId: NodeJS.Timeout;
const timeout = new Promise<T>((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error(`${message} - ${ms}ms`));
}, ms);
});
// @ts-ignore
return [timeout, timeoutId];
}
// Asynchronous sleep function. Returns a Promise that resolves after |ms|
// milliseconds.
export function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
|
package com.example.workschedule.data.database.trainrun
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.example.workschedule.data.database.DateTimeConverter
import com.example.workschedule.data.database.PeriodicityConverter
import com.example.workschedule.domain.models.TrainPeriodicity
import java.time.LocalDateTime
/**
* Table structure for the list of routes
*/
@Entity
@TypeConverters(DateTimeConverter::class, PeriodicityConverter::class)
data class TrainRunEntity(
@PrimaryKey(autoGenerate = true)
@field:ColumnInfo(name = "id")
val id: Int,
@field:ColumnInfo(name = "trainId")
val trainId: Int,
@field:ColumnInfo(name = "trainNumber")
val trainNumber: Int,
@field:ColumnInfo(name = "trainDirection")
val trainDirection: String,
@field:ColumnInfo(name = "trainPeriodicity")
val trainPeriodicity: TrainPeriodicity,
@field:ColumnInfo(name = "driverId")
val driverId: Int,
@field:ColumnInfo(name = "driverName")
val driverName: String,
@field:ColumnInfo(name = "startTime")
val startTime: LocalDateTime,
@field:ColumnInfo(name = "travelTime")
val travelTime: Long,
@field:ColumnInfo(name = "travelRestTime")
val travelRestTime: Long,
@field:ColumnInfo(name = "backTravelTime")
val backTravelTime: Long
)
|
<?php include 'includes/header.php';
class Transporte {
public function __construct(protected int $ruedas, protected int $capacidad){
}
public function getInfo() : string {
return "El transporte tiene ". $this->ruedas . " y una capacidad de " . $this->capacidad . " personas ";
}
public function getRuedas() : int{
return $this->ruedas;
}
}
class Bicicleta extends Transporte {
public function getInfo() : string {
return "El transporte tiene ". $this->ruedas . " y una capacidad de " . $this->capacidad . " personas y NO GASTA GASOLINA ";
}
}
class Automovil extends Transporte {
public function __construct(protected int $ruedas, protected int $capacidad, protected string $transmicion){
}
public function getTransmicion() : string {
return $this->transmicion;
}
}
$bicicleta = new Bicicleta(2,1);
echo $bicicleta->getInfo();
echo $bicicleta->getRuedas();
echo "<hr>";
$auto = new Automovil(4 , 4, "Manual");
echo $auto->getInfo();
echo $auto->getTransmicion();
include 'includes/footer.php';
|
# Endpoint
An endpoint is one single REST endpoint that can be hit.
It is limited to one REST method.
To have one endpoint with multiple methods, see Group.
## Properties
```typescript
type endpoint = {
method: HTTPMethod;
response: Data;
body?: Data;
path: String;
description?: String;
error?: Data;
params?: Data;
}
```
### Method
The REST Method, one of `GET`, `POST`, `PUT`, `OPTIONS`, `DELETE`or `PATCH`.
### Response
The structure of the data that is expected to be returned. See [data](./data.md) for more details.
### Body
Optionally descibe the data that is expected for this payload. For `GET` requests, this would be omitted
### Error
Optionally provide what a payload would look like if an error is returned outside of the standard status code and message.
### Path
The path this endpoint will serve.
### Params
If path params are inclduded, use a data type object to describe the expected data types for each path parameter.
### Description
> **Note**
> perhaps change to use /// to denote a description above the object like Rust docs
Optionally Describe this endpoint with a string body.
## Examples
```
endpoint GetBrand = {
method: "POST",
response: Brand,
body: CreateBodyPayload,
path: "/brands/:id",
description: "Pull info on a single Brand"
}
```
|
import { Component } from '@angular/core';
import { MenuItem } from 'primeng/api';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent {
items!: MenuItem[];
ngOnInit() {
this.items = [
{
label: 'Home',
icon: 'pi pi-star',
routerLink: ['/']
},
{
label: 'Estudos',
icon: 'pi pi-book',
routerLink: ['/estudo'],
},
{
label: 'Projetos',
icon: 'pi pi-folder-open',
items: [
{
label: 'Html-Css',
routerLink: ['/htmlcss']
},
{
label: 'Java',
routerLink: ['/java']
},
{
label: 'React',
routerLink: ['/react']
},
{
label: 'Angular',
routerLink: ['/angular']
},
{
label: 'ApiRest',
routerLink: ['/apirest']
},
{
label: 'Micro-Serviço',
routerLink: ['/microservico']
}
]
},
{
label: 'Gráficos',
icon: 'pi pi-chart-bar'
},
{
label: 'Sobre',
icon: 'pi pi-eye',
routerLink: ['/sobre']
},
{
label: 'Login',
icon: 'pi pi-sign-in'
}
]
}
}
|
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Edition } from '../../../models/entities/edition';
import { ActivatedRoute, Router } from '@angular/router';
import { WpService } from '../../../services/wp.service';
import { Title } from '@angular/platform-browser';
import { Subscription, concatMap, of, tap } from 'rxjs';
import { News } from '../../../models/entities/news';
import { Event } from '../../../models/entities/event';
import { environment } from '../../../../environments/environment';
import { Media } from '../../../models/entities/media';
import { MediaService } from '../../../services/media.service';
import { LoadingService } from '../../../services/loading.service';
import { ViewportScroller } from '@angular/common';
import { CoverImage } from '../../../models/entities/cover';
import { MetaService } from '../../../services/meta.service';
@Component({
selector: 'app-edition-detail',
templateUrl: './edition-detail.component.html',
styleUrl: './edition-detail.component.css',
})
export class EditionDetailComponent implements OnInit, OnDestroy {
private _subscriptions: Subscription = new Subscription();
private _appTitle = environment.appTitle;
edition!: Edition;
events!: Event[];
news!: News[];
shareData?: ShareData;
coverImage?: CoverImage;
constructor(
private _router: Router,
private _route: ActivatedRoute,
private _wpService: WpService,
private _mediaService: MediaService,
private _loadingService: LoadingService,
private _titleService: Title,
private _metaService: MetaService,
private _viewportScroller: ViewportScroller
) {}
ngOnInit(): void {
this.getEdition();
}
ngOnDestroy(): void {
this._subscriptions.unsubscribe();
}
private getEdition(): void {
const sub = this._route.data
.pipe(
tap(({ data }) => {
if (data) {
this._viewportScroller.scrollToPosition([0, 0]);
this.initEdition(data);
} else {
throw new Error('No edition found');
}
}),
concatMap(() => {
if (this.edition.featuredMediaId && this.edition.featuredMediaId > 0) {
return this._wpService.getMediaById(this.edition.featuredMediaId);
}
return of(null);
}),
concatMap((featuredMedia) => {
if (featuredMedia) {
this.edition.featuredMedia = this.initFeaturedMedia(featuredMedia);
this.initCoverImage();
}
if (this.edition.galleryMediaIds && this.edition.galleryMediaIds.length > 0) {
return this._wpService.getMediaByIds(this.edition.galleryMediaIds);
}
return of(null);
}),
concatMap((galleryMedia) => {
if (galleryMedia) {
this.edition.galleryMedia = this.initGalleryMedia(galleryMedia);
}
return this._wpService.getEventsByEditionId(this.edition.id, 8);
}),
concatMap((events) => {
if (events && events.length > 0) {
this.initEvents(events);
const mediaIds = this.events.map((x) => x.featuredMediaId).filter((id) => id !== null);
if (mediaIds && mediaIds.length > 0) {
return this._wpService.getMediaByIds(mediaIds);
} else {
return of([]);
}
}
return of([]);
}),
concatMap((eventsFeaturedMedia) => {
if (eventsFeaturedMedia && eventsFeaturedMedia.length > 0) {
this.mapEventsMedia(eventsFeaturedMedia);
}
return this._wpService.getNewsByEditionId(this.edition.id, 8);
}),
concatMap((news) => {
if (news && news.length > 0) {
this.initNews(news);
const mediaIds = this.news.map((x) => x.featuredMediaId).filter((id) => id !== null);
if (mediaIds && mediaIds.length > 0) {
return this._wpService.getMediaByIds(mediaIds);
} else {
return of([]);
}
}
return of([]);
}),
tap((newsFeaturedMedia) => {
if (newsFeaturedMedia && newsFeaturedMedia.length > 0) {
this.mapNewsMedia(newsFeaturedMedia);
}
})
)
.subscribe({
next: () => {
this.initTitle();
this.initMetaData();
this.initShareData();
this._loadingService.set(false);
},
error: (error) => {
console.error('Error:', error);
this._loadingService.set(false);
},
});
this._subscriptions.add(sub);
}
private initEdition(edition: any): void {
this.edition = new Edition();
this.edition.id = edition.id;
this.edition.title = edition.title.rendered;
this.edition.content = edition.content.rendered;
this.edition.excerpt = edition.excerpt.rendered;
this.edition.featuredMediaId = edition.featured_media;
this.edition.galleryMediaIds = edition.acf.gallery;
this.edition.coverTitle = edition.acf.cover_title;
this.edition.coverLinkSlug = edition.cover_link_info?.slug;
this.edition.coverLinkPostType = edition.cover_link_info?.post_type;
}
private initCoverImage(): void {
this.coverImage = new CoverImage();
this.coverImage.media = this.edition.featuredMedia;
this.coverImage.showTitle = true;
this.coverImage.title = this.edition.title;
this.coverImage.linkSlug = this.edition.coverLinkSlug;
this.coverImage.linkPostType = this.edition.coverLinkPostType;
}
private initFeaturedMedia(media: any): Media {
let featuredMedia = new Media();
featuredMedia.id = media.id;
featuredMedia.link = media.link;
featuredMedia.size = this._mediaService.mapMediaSize(media);
return featuredMedia;
}
private initGalleryMedia(mediaArray: any[]): Media[] {
const galleryMedia = mediaArray.map((media) => {
let galleryItem = new Media();
galleryItem.id = media.id;
galleryItem.link = media.link;
galleryItem.size = this._mediaService.mapMediaSize(media);
return galleryItem;
});
return galleryMedia;
}
private initEvents(events: any[]): void {
this.events = events.map((data) => {
let event = new Event();
event.slug = data.slug;
event.date = data.date;
event.title = data.title.rendered;
event.excerpt = data.excerpt.rendered;
event.featuredMediaId = data.featured_media;
return event;
});
}
private mapEventsMedia(media: any[]): void {
media.forEach((mediaItem) => {
const eventItem = this.events.find((x) => x.featuredMediaId === mediaItem.id);
if (eventItem) {
eventItem.featuredMedia = this.initFeaturedMedia(mediaItem);
}
});
}
private initNews(news: any[]): void {
this.news = news.map((data) => {
let news = new News();
news.slug = data.slug;
news.date = data.date;
news.title = data.title.rendered;
news.excerpt = data.excerpt.rendered;
news.featuredMediaId = data.featured_media;
return news;
});
}
private mapNewsMedia(media: any[]): void {
media.forEach((mediaItem) => {
const newsItem = this.news.find((x) => x.featuredMediaId === mediaItem.id);
if (newsItem) {
newsItem.featuredMedia = this.initFeaturedMedia(mediaItem);
}
});
}
private initTitle(): void {
if (this.edition.title) {
this._titleService.setTitle(this.edition.title + ' - ' + this._appTitle);
} else {
this._titleService.setTitle(this._appTitle);
}
}
private initMetaData(): void {
this._metaService.updateBaseTitle(this._metaService.formatDescription(this.edition.title));
this._metaService.updateBaseDescription(this._metaService.formatDescription(this.edition.excerpt));
this._metaService.updateUrl(environment.baseUrl + this._router.url);
this._metaService.updateTitle(this._metaService.formatDescription(this.edition.title));
this._metaService.updateDescription(this._metaService.formatDescription(this.edition.excerpt));
this._metaService.updateImage(this.edition?.featuredMedia?.size?.xLarge?.src ?? '');
}
initShareData() {
this.shareData = { title: '', text: '', url: '' };
this.shareData.title = this.edition.title.replace(/<[^>]*>/g, '');
this.shareData.text = this.edition.excerpt.replace(/<[^>]*>/g, '');
this.shareData.url = environment.baseUrl + this._router.url;
}
}
|
package poo.exercicio1;
public abstract class Conta {
private int agencia;
private int conta;
private String titular;
private int limite;
private double saldo;
private int valorLimite;
public Conta(int agencia, int conta, String titular, int limite, int valorLimite) {
this.agencia = agencia;
this.conta = conta;
this.titular = titular;
this.limite = limite;
this.valorLimite = valorLimite;
}
public Conta(int agencia, int conta, String titular, int limite, int valorLimite, double saldo) {
this(agencia, conta, titular, limite, valorLimite);
this.saldo = saldo;
}
public abstract void sacar(int valor) throws SaldoInsuficienteException, IllegalArgumentException;
public void depositar(int valor) throws IllegalArgumentException {
if(valor > 0) {
double saldo = getSaldo() + valor;
setSaldo(saldo);
} else {
throw new IllegalArgumentException("Valor para depósito inválido!");
}
}
public void setValorLimite(int valorLimite) throws LimiteInvalidoException {
this.valorLimite = valorLimite;
if(valorLimite < 0) {
throw new LimiteInvalidoException("Valor de ajuste de limite inválido");
}
}
public int getAgencia() {
return agencia;
}
public void setAgencia(int agencia) {
this.agencia = agencia;
}
public int getConta() {
return conta;
}
public void setConta(int conta) {
this.conta = conta;
}
public String getTitular() {
return titular;
}
public void setTitular(String titular) {
this.titular = titular;
}
public int getLimite() {
return limite;
}
public void setLimite(int limite) {
this.limite = limite;
}
public double getSaldo() {
return saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
public int getValorLimite() {
return valorLimite;
}
@Override
public String toString() {
String out = "";
out+= "Agência: " + agencia + "\n";
out+= "Nome do Titular: " + titular + "\n";
out+= "Número da Conta: " + conta + "\n";
out+= "Saldo Atual R$ " + saldo + "\n";
out+= "Limite Atual R$ " + limite + "\n";
out+= "Valor de limite oferecido pelo banco R$ " + valorLimite + "\n";
return out;
}
}
|
import React from "react";
import PropTypes from "prop-types";
import styled, { css } from "styled-components";
import { doNothing } from "..";
const StyledLink = styled.a`
${({ color, active, hover, visited }) => css`
color: ${color};
cursor: pointer;
transition: color 0.2s linear;
:hover {
color: ${hover};
}
:active {
color: ${active};
}
:visited {
color: ${visited};
}
`}
`;
const AkLink = ({
href,
onClick = doNothing,
color,
active,
visited,
hover,
children,
}) => {
return (
<StyledLink
href={href}
onClick={onClick}
color={color}
active={active}
visited={visited}
hover={hover}
>
{children}
</StyledLink>
);
};
AkLink.propTypes = {
href: PropTypes.string,
onClick: PropTypes.func.isRequired,
color: PropTypes.string,
active: PropTypes.string,
visited: PropTypes.string,
hover: PropTypes.string,
children: PropTypes.node.isRequired,
};
export default AkLink;
|
<template>
<div id="app">
<button @click="changeTheme">theme switch</button>
<button @click="changeLang">language switch</button>
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld :msg="$t('helloworld.main_title')" />
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
name: "App",
components: {
HelloWorld
},
mounted() {
this.loadTheme();
},
methods: {
loadTheme() {
document.body.classList.add("app-background");
const theme = localStorage.getItem("theme");
if (theme === "dark") {
document.documentElement.setAttribute("theme", "dark");
} else {
document.documentElement.setAttribute("theme", "light");
}
},
changeTheme() {
const theme = localStorage.getItem("theme");
if (theme !== "dark") {
localStorage.setItem("theme", "dark");
document.documentElement.setAttribute("theme", "dark");
} else {
localStorage.setItem("theme", "light");
document.documentElement.setAttribute("theme", "light");
}
},
changeLang() {
const lang = localStorage.getItem("lang");
this.changeRTL();
if (lang === "en") {
localStorage.setItem("lang", "fa");
this.$i18n.locale = "fa";
} else {
localStorage.setItem("lang", "en");
this.$i18n.locale = "en";
}
},
changeRTL() {
const rtl = localStorage.getItem("rtl");
if (rtl === "0") {
localStorage.setItem("rtl", 1);
document.body.classList.remove("rtl");
} else {
localStorage.setItem("rtl", 0);
document.body.classList.add("rtl");
}
}
}
};
</script>
<style lang="scss">
@import "style/main";
.rtl {
text-align: right;
direction: rtl;
}
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
|
@model CustomerRegisterViewModel;
@{
ViewData["Style"] = "Style.css";
}
<!-- Start Register -->
<section class="ec-page-content section-space-p">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<div class="section-title">
<h2 class="ec-bg-title">ثبت نام</h2>
<h2 class="ec-title">ثبت نام</h2>
<p class="sub-title mb-3">بهترین مکان برای خرید و فروش محصولات دیجیتال</p>
</div>
</div>
<div class="ec-register-wrapper">
<div class="ec-register-container">
<div class="ec-register-form">
<form asp-action="CustomerRegister" method="post">
<span class="ec-register-wrap">
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
</span>
<span class="ec-register-wrap ec-register-half">
<label asp-for="@Model.FirstName" class="form-text"></label>
<span asp-validation-for="@Model.FirstName" class="text-danger"></span>
<input asp-for="@Model.FirstName" class="form-controller" placeholder="نام خود را وارد کنید">
</span>
<span class="ec-register-wrap ec-register-half">
<label asp-for="@Model.LastName" class="form-text"></label>
<span asp-validation-for="@Model.LastName" class="text-danger"></span>
<input asp-for="@Model.LastName" class="form-controller" placeholder="نام خانوادگی خود را وارد کنید">
</span>
<span class="ec-register-wrap">
<label asp-for="@Model.Email" class="form-text"></label>
<span asp-validation-for="@Model.Email" class="text-danger"></span>
<input asp-for="@Model.Email" class="form-controller" placeholder="وارد کردن ایمیل ">
</span>
<span class="ec-register-wrap ec-register-half">
<label asp-for="@Model.Password" class="form-text"></label>
<span asp-validation-for="@Model.Password" class="text-danger"></span>
<input asp-for="@Model.Password" class="form-controller" placeholder="رمز عبور">
</span>
<span class="ec-register-wrap ec-register-half">
<label asp-for="@Model.ConfirmPassword" class="form-text"></label>
<span asp-validation-for="@Model.ConfirmPassword" class="text-danger"></span>
<input asp-for="@Model.ConfirmPassword" class="form-controller" placeholder="تکرار رمز عبور">
</span>
<span class="ec-register-wrap">
<label asp-for="@Model.Address" class="form-text"></label>
<span asp-validation-for="@Model.Address" class="text-danger"></span>
<input asp-for="@Model.Address" class="form-controller" placeholder="آدرس خط اول">
</span>
<span class="ec-register-wrap">
<label asp-for="@Model.ProvinceId" class="form-text"></label>
<span asp-validation-for="@Model.ProvinceId" class="text-danger"></span>
<span class="ec-rg-select-inner">
<select asp-for="@Model.ProvinceId" class="form-controller">
<option selected="" disabled="">استان </option>
@foreach (var item in Model.provinces)
{
<option value="@item.Id">@item.Name</option>
}
</select>
</span>
</span>
<span class="ec-register-wrap ec-register-half">
<label asp-for="@Model.City" class="form-text"></label>
<span asp-validation-for="@Model.City" class="text-danger"></span>
<input asp-for="@Model.City" placeholder="نام شهر خود ">
</span>
<span class="ec-register-wrap ec-register-half">
<label asp-for="@Model.PostalCode" class="form-text"></label>
<span asp-validation-for="@Model.PostalCode" class="text-danger"></span>
<input asp-for="@Model.PostalCode" placeholder="کد پستی را واردن کنید ">
</span>
@* <span class="ec-register-wrap ec-recaptcha">
<span class="g-recaptcha" data-sitekey="6LfKURIUAAAAAO50vlwWZkyK_G2ywqE52NU7YO0S"
data-callback="verifyRecaptchaCallback"
data-expired-callback="expiredRecaptchaCallback"></span>
<input class="form-control d-none" data-recaptcha="true" required=""
data-error="Please complete the Captcha">
<span class="help-block with-errors"></span>
</span>*@
<span class="ec-register-wrap ec-register-btn">
<button class="btn btn-primary" type="submit">ثبت نام</button>
</span>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End Register -->
|
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Paths } from 'src/app/app-routing.module';
import { HistoryPage } from 'src/app/shared/abstract-sources/history-page.component';
@Component({
selector: 'app-academic-history',
templateUrl: './academic-history.component.html',
styleUrls: ['./academic-history.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AcademicHistoryComponent extends HistoryPage {
paths = Paths;
academicHistory: Record<any, AcademicItemObject>[] = [
{
'pt-BR': {
title: 'MBA em Ciência de Dados',
institute: 'Universidade de Fortaleza',
instituteURL: 'https://unifor.br/',
description: 'Curso para formação de profissionais qualificados para realizar projetos de desenvolvimento e administração de soluções de Ciências de Dados trabalhando com tecnologias que permitam operar grandes volumes de dados processados.',
startDate: 'Abril/2024',
endDate: 'Fevereiro/2026 (Cursando)'
},
'en-US': {
title: 'MBA in Data Science',
institute: 'University of Fortaleza',
instituteURL: 'https://unifor.br/',
description: 'Course to train qualified professionals to carry out projects to develop and manage Data Science solutions, working with technologies that allow the operation of large volumes of processed data.',
startDate: 'April/2024',
endDate: 'February/2026 (In progress)'
}
},
{
'pt-BR': {
title: 'Bacharelado em Ciência da Computação ',
institute: 'Universidade de Fortaleza',
instituteURL: 'https://unifor.br/',
description: 'Curso voltado ao aprendizado de ferramentas de infraestrutura de software, sistemas de computação, métodos, teorias, linguagens e modelos, além de resolução de problemas que tenham solução algorítmica e desenvolvimento de sistemas e projetos de qualquer natureza computacional com equipes de diferentes perfis.',
startDate: 'Janeiro/2019',
endDate: 'Dezembro/2023',
credential: 'https://imgur.com/a/MweFo8c'
},
'en-US': {
title: 'Bachelor in Computer Science ',
institute: 'University of Fortaleza',
instituteURL: 'https://unifor.br/',
description: 'Course aimed at learning about software infrastructure tools, computer systems, methods, theories, languages and models, as well as solving problems with algorithmic solutions and developing systems and projects of any computational nature with teams of different profiles.',
startDate: 'January/2019',
endDate: 'December/2023',
credential: 'https://imgur.com/a/MweFo8c'
}
}
];
}
interface AcademicItemObject {
title: string,
institute: string,
instituteURL?: string,
description?: string,
startDate: string,
endDate?: string,
credential?: string
}
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Register {
string public github;
address public owner;
struct Referral {
address referralAddress;
string referralString;
}
Referral[] public referrals;
constructor() {
github = "Cummingloud";
owner = 0xeC8dD93C481cBE0c8658f7673f16343a72xxxxx;
}
function addReferral(address _referralAddress, string memory _referralString) external {
require(msg.sender == owner, "Only the owner can add referrals.");
referrals.push(Referral(_referralAddress, _referralString));
}
function totalReferrals() public view returns (uint256) {
return referrals.length;
}
}
|
/* eslint-disable @next/next/no-img-element */
"use client";
import NavLink from "./NavLink";
import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import Link from "next/link";
import clsx from "clsx";
import useMobile from "@/hooks/useMobile";
const navigation = [
{
title: "couple",
// href: "/story",
target: "couple", // Thêm target tương ứng với ID của phần cần scroll đến
},
{
title: "stories",
// href: "/gallery",
target: "story",
},
{
title: "memories",
// href: "/event",
target: "sweetMemory",
},
{
title: "wedding",
// href: "/attending",
target: "ourWedding",
},
];
type Props = {
changeText: boolean;
};
export default function Navigation({ changeText }: Props) {
const [isActive, setIsActive] = useState<string>("");
const isMobile = useMobile();
const handleNavLinkClick = (key: string) => {
setIsActive(key);
if (key === "couple") {
window.scrollTo({
top: isMobile ? 620 : 700,
behavior: "smooth",
});
}
if (key === "story") {
window.scrollTo({
top: isMobile ? 2250 : 1900,
behavior: "smooth",
});
}
if (key === "sweetMemory") {
window.scrollTo({
top: isMobile ? 5000 : 4300,
behavior: "smooth",
});
}
if (key === "ourWedding") {
window.scrollTo({
top: isMobile ? 6800 : 5900,
behavior: "smooth",
});
}
};
return (
<div className="w-full flex md:justify-center items-center">
<div className="flex items-center gap-x-6 md:gap-5">
{navigation.map((nav, index) => {
const active = nav.target === isActive;
if (index === Math.ceil(navigation.length / 2)) {
return (
<>
<button
key={index}
onClick={() => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
}}
>
<img
src="/assets/images/logo.png"
alt="Logo"
className="w-10 h-10 md:w-20 md:h-20 rounded-full"
/>
</button>
<button
key={nav.title}
className={clsx(
"font-semibold text-xs md:text-base hover:text-primary",
{
"text-white": !changeText && !active,
"text-black": changeText && !active,
"text-primary": active,
}
)}
onClick={() => handleNavLinkClick(nav.target)}
>
{nav.title.toLocaleUpperCase()}
</button>
</>
);
}
return (
<button
key={nav.title}
className={clsx(
"font-semibold text-xs md:text-base hover:text-primary",
active && "text-primary",
{
"text-white": !changeText,
"text-black": changeText,
}
)}
onClick={() => handleNavLinkClick(nav.target)}
>
{nav.title.toLocaleUpperCase()}
</button>
);
})}
</div>
</div>
);
}
|
/*
*
* This file is part of Kopycat emulator software.
*
* Copyright (C) 2022 INFORION, LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Non-free licenses may also be purchased from INFORION, LLC,
* for users who do not want their programs protected by the GPL.
* Contact us for details [email protected]
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package ru.inforion.lab403.kopycat.library.types
import ru.inforion.lab403.common.logging.INFO
import ru.inforion.lab403.common.logging.logger
import ru.inforion.lab403.common.utils.DynamicClassLoader
import ru.inforion.lab403.kopycat.Kopycat
import ru.inforion.lab403.kopycat.library.exceptions.ResourceGzipError
import java.io.*
import java.nio.file.Path
import java.util.zip.GZIPInputStream
import kotlin.io.path.*
class ResourceNotFoundException(val path: String) : FileNotFoundException(
"Can't open resource within path '$path'. " +
"Searched in resource runtime directory and JAR resource"
) {
constructor(path: Path) : this(path.pathString)
}
/**
* Searches the resource within JAR resources and runtime provided resource path
*
* Search priority:
* 1. Runtime path
* 2. JAR resources
*
* @throws FileNotFoundException Is the resource not found
*/
class Resource(val path: Path) {
constructor(path: String) : this(Path(path))
companion object {
@Transient
val log = logger(INFO)
}
/**
* Path string with POSIX-like separators
*/
val pathString: String = path.invariantSeparatorsPathString
fun openStream(): InputStream {
return let {
// WARNING: don't change -> with function not working
val runtimePath = Path(Kopycat.resourceDir) / path
if (runtimePath.exists()) {
return@let File(runtimePath.toString()).inputStream()
}
log.trace { "Runtime file '${runtimePath}' not found, trying to load JAR resource" }
return@let DynamicClassLoader.getResourceAsStream(pathString)
}.let { resource ->
if (resource == null) {
throw ResourceNotFoundException(pathString)
}
resource
}.let { stream ->
if (path.extension == "gz") try {
GZIPInputStream(stream)
} catch (e: IOException) {
throw ResourceGzipError(path, e)
} else stream
}
}
fun readBytes(): ByteArray = openStream().readBytes()
}
|
---
title: ReportBuildOptions Enum
linktitle: ReportBuildOptions
articleTitle: ReportBuildOptions
second_title: Aspose.Words för .NET
description: Aspose.Words.Reporting.ReportBuildOptions uppräkning. Anger alternativ som styr beteendet förReportingEngine medan du bygger en rapport i C#.
type: docs
weight: 4720
url: /sv/net/aspose.words.reporting/reportbuildoptions/
---
## ReportBuildOptions enumeration
Anger alternativ som styr beteendet för[`ReportingEngine`](../reportingengine/) medan du bygger en rapport.
```csharp
[Flags]
public enum ReportBuildOptions
```
### Värderingar
| namn | Värde | Beskrivning |
| --- | --- | --- |
| None | `0` | Anger standardalternativ. |
| AllowMissingMembers | `1` | Anger att saknade objektmedlemmar ska behandlas som noll-literals av motorn. Det här alternativet påverkar endast åtkomst till instanser (det vill säga icke-statiska) objektmedlemmar och tilläggsmetoder. Om detta -alternativ inte är inställt, skapar motorn ett undantag när den stöter på en saknad objektmedlem. |
| RemoveEmptyParagraphs | `2` | Anger att motorn ska ta bort stycken som blir tomma efter att mallsyntaxtaggar har tagits bort eller ersatts med tomma värden. |
| InlineErrorMessages | `4` | Anger att motorn ska infoga mallsyntaxfelmeddelanden i utdatadokument. Om det här alternativet inte är inställt skapar motorn ett undantag när ett syntaxfel stöter på. |
| UseLegacyHeaderFooterVisiting | `8` | Anger att motorn ska besöka sektionens underordnade noder (sidhuvuden, sidfötter, kroppar) i en order som är kompatibel med Aspose.Words-versioner före 21.9. |
| RespectJpegExifOrientation | `10` | Anger att motorn ska använda EXIF-bildorienteringsvärden för att korrekt rotera infogade JPEG-bilder. |
### Se även
* namnutrymme [Aspose.Words.Reporting](../../aspose.words.reporting/)
* hopsättning [Aspose.Words](../../)
|
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header d-flex justify-content-between">
{{ $channel->name }}
<a href="{{ route('channels.upload-videos.index', ['channel' => $channel->id]) }}">Upload Videos</a>
</div>
<div class="card-body">
<form id="update-channel-form"
action="{{ route('channels.update', $channel->id) }}"
method="post"
enctype="multipart/form-data">
@csrf
@method('patch')
<div class="form-group row justify-content-center">
<div class="channel-avatar">
@if ($channel->editable())
<div class="channel-avatar-overlay"
onclick="document.getElementById('avatar').click()">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 60 60" style="enable-background:new 0 0 60 60;" xml:space="preserve" width="50px" height="50px" class=""><g><g>
<path d="M55.201,15.5h-8.524l-4-10H17.323l-4,10H12v-5H6v5H4.799C2.152,15.5,0,17.652,0,20.299v29.368 C0,52.332,2.168,54.5,4.833,54.5h50.334c2.665,0,4.833-2.168,4.833-4.833V20.299C60,17.652,57.848,15.5,55.201,15.5z M8,12.5h2v3H8 V12.5z M58,49.667c0,1.563-1.271,2.833-2.833,2.833H4.833C3.271,52.5,2,51.229,2,49.667V20.299C2,18.756,3.256,17.5,4.799,17.5H6h6 h2.677l4-10h22.646l4,10h9.878c1.543,0,2.799,1.256,2.799,2.799V49.667z" data-original="#000000" class="active-path" data-old_color="#ffffff" fill="#ffffff"/>
<path d="M30,14.5c-9.925,0-18,8.075-18,18s8.075,18,18,18s18-8.075,18-18S39.925,14.5,30,14.5z M30,48.5c-8.822,0-16-7.178-16-16 s7.178-16,16-16s16,7.178,16,16S38.822,48.5,30,48.5z" data-original="#000000" class="active-path" data-old_color="#ffffff" fill="#ffffff"/>
<path d="M30,20.5c-6.617,0-12,5.383-12,12s5.383,12,12,12s12-5.383,12-12S36.617,20.5,30,20.5z M30,42.5c-5.514,0-10-4.486-10-10 s4.486-10,10-10s10,4.486,10,10S35.514,42.5,30,42.5z" data-original="#000000" class="active-path" data-old_color="#ffffff" fill="#ffffff"/>
<path d="M52,19.5c-2.206,0-4,1.794-4,4s1.794,4,4,4s4-1.794,4-4S54.206,19.5,52,19.5z M52,25.5c-1.103,0-2-0.897-2-2s0.897-2,2-2 s2,0.897,2,2S53.103,25.5,52,25.5z" data-original="#000000" class="active-path" data-old_color="#ffffff" fill="#ffffff"/>
</g></g> </svg>
</div>
@endif
<img src="{{ $channel->avatar }}" alt="">
</div>
</div>
@if ( ! $channel->editable())
<div class="">
<h4 class="text-center">{{ $channel->name }}</h4>
<p class="text-center">{{ $channel->description }}</p>
</div>
@endif
<div class="text-center">
<subscribe-button :channel="{{ $channel }}"
:initial-subscriptions="{{ $channel->subscriptions }}" />
</div>
@if ($channel->editable())
<input type="file" name="avatar"
id="avatar" class="d-none"
onchange="document.getElementById('update-channel-form').submit()">
<div class="form-group">
<label for="name" class="form-control-label">Your channel name</label>
<input type="text" id="name" name="name" class="form-control" value="{{ $channel->name }}">
</div>
<div class="form-group">
<label for="description" class="form-control-label">Description</label>
<textarea name="description" id="description" rows="5" class="form-control">{{ $channel->description }}</textarea>
</div>
@if ($errors->any())
<ul class="list-group mb-3">
@foreach ($errors->all() as $error)
<li class="list-group-item text-danger">{{ $error }}</li>
@endforeach
</ul>
@endif
<button type="submit" class="btn btn-info">Update Your Channel</button>
@endif
</form>
</div>
</div>
<div class="card">
<div class="card-header">Videos</div>
<div class="card-body">
<table class="table">
<thead>
<th>#</th>
<th>Image</th>
<th>Title</th>
<th>Views</th>
<th>Status</th>
<th></th>
</thead>
<tbody>
@foreach ($videos as $k => $video)
<tr>
<td>{{ $k + 1 }}</td>
<td>
<img src="{{ $video->thumbnail }}" alt="video thumbnail" width="100px">
</td>
<td>{{ $video->title }}</td>
<td>{{ $video->views }}</td>
<td>{{ $video->percentage === 100 ? 'Live' : 'Processing' }}</td>
<td>
@if ($video->percentage === 100)
<a href="{{ route('videos.show', $video->id) }}"
target="_blank" class="btn btn-sm btn-outline-primary">View</a>
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="row justify-content-center">
{{ $videos->links() }}
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
|
<!DOCTYPE html>
<html lang="zh">
<head>
<title>接雨水 II</title>
<link rel="shortcut icon" href="/static/favicon.ico">
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="/static/detail.css">
</head>
<body>
<div class="container mt-3">
<header class="problem-header">
<h1>接雨水 II</h1>
</header>
<main>
<article class="problem-content">
<p>标签:
<a href="/problems?tag=breadth-first-search" class="badge bg-secondary tag-link">广度优先搜索</a>
<a href="/problems?tag=array" class="badge bg-secondary tag-link">数组</a>
<a href="/problems?tag=matrix" class="badge bg-secondary tag-link">矩阵</a>
<a href="/problems?tag=heap-priority-queue" class="badge bg-secondary tag-link">堆(优先队列)</a>
</p>
<p>难度: <span class="badge bg-secondary">Hard</span></p>
<div class="problem-description">
<p>给你一个 <code>m x n</code> 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。</p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg" /></p>
<pre>
<strong>输入:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
<strong>输出:</strong> 4
<strong>解释:</strong> 下雨后,雨水将会被上图蓝色的方块中。总的接雨水量为1+2+1=4。
</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg" /></p>
<pre>
<strong>输入:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
<strong>输出:</strong> 10
</pre>
<p><strong>提示:</strong></p>
<ul>
<li><code>m == heightMap.length</code></li>
<li><code>n == heightMap[i].length</code></li>
<li><code>1 <= m, n <= 200</code></li>
<li><code>0 <= heightMap[i][j] <= 2 * 10<sup>4</sup></code></li>
</ul>
</div>
</article>
<section>
<h2>Submission</h2>
<div class="code-block">
<p>运行时间: 126 ms</p>
<p>内存: 18.5 MB</p>
<pre class="bg-light p-2 code-pre">class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
m,n = len(heightMap),len(heightMap[0])
min_height = []
water = [[-1 for j in range(n)] for i in range(m)]
# top&low
for j in range(n):
heapq.heappush(min_height,(heightMap[0][j],0,j))
water[0][j] = heightMap[0][j]
heapq.heappush(min_height,(heightMap[m-1][j],m-1,j))
water[m-1][j] = heightMap[m-1][j]
# lf&rt
for i in range(1,m-1):
heapq.heappush(min_height,(heightMap[i][0],i,0))
water[i][0] = heightMap[i][0]
heapq.heappush(min_height,(heightMap[i][n-1],i,n-1))
water[i][n-1] = heightMap[i][n-1]
self.ans = 0
def cal_water(h,i,j):
if heightMap[i][j] >= h:
water[i][j] = heightMap[i][j]
else:
self.ans += h - heightMap[i][j]
water[i][j] = h
heapq.heappush(min_height, (water[i][j],i,j))
while min_height:
h, i, j = heapq.heappop(min_height)
if i > 0 and water[i-1][j] == -1:
cal_water(h,i-1,j)
if i < m-1 and water[i+1][j] == -1:
cal_water(h,i+1,j)
if j > 0 and water[i][j-1] == -1:
cal_water(h,i,j-1)
if j < n-1 and water[i][j+1] == -1:
cal_water(h,i,j+1)
return self.ans
</pre>
<button class="btn btn-secondary copy-btn" onclick="copyCode(this)">复制代码</button>
</div>
</section>
<section class="vote-buttons">
<button id="like-button" class="btn btn-outline-success"><i class="fas fa-thumbs-up"></i><span id="like-count" class="vote-count">0</span></button>
<button id="dislike-button" class="btn btn-outline-danger"><i class="fas fa-thumbs-down"></i><span id="dislike-count" class="vote-count">0</span></button>
</section>
<section class="explain-section">
<h2>Explain</h2>
<div class="card">
<div class="card-header" id="explainHeader">
<span class="mb-0">
<button class="btn btn-link btn-block text-start collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#explainCollapse" aria-expanded="false" aria-controls="explainCollapse">
<i class="fas fa-chevron-down float-end"></i>
</button>
</span>
</div>
<div id="explainCollapse" class="collapse" aria-labelledby="explainHeader">
<div class="card-body">
<p>该题解使用了最小堆来解决接雨水问题。首先将矩阵周边的元素加入最小堆,并初始化水位数组water。然后不断从堆顶取出高度最小的元素,判断其四周是否有未访问过的元素,如果有就计算该位置能接的雨水量,并将其加入最小堆。重复这个过程直到堆为空,最终的接雨水总量就是答案。</p>
<p>时间复杂度: O(mn * log(mn))</p>
<p>空间复杂度: O(mn)</p>
<pre class="bg-light p-2">class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
m,n = len(heightMap),len(heightMap[0])
min_height = []
water = [[-1 for j in range(n)] for i in range(m)] # 初始化water数组,-1表示未访问过
# 将矩阵上下边界加入最小堆
for j in range(n):
heapq.heappush(min_height,(heightMap[0][j],0,j))
water[0][j] = heightMap[0][j]
heapq.heappush(min_height,(heightMap[m-1][j],m-1,j))
water[m-1][j] = heightMap[m-1][j]
# 将矩阵左右边界加入最小堆
for i in range(1,m-1):
heapq.heappush(min_height,(heightMap[i][0],i,0))
water[i][0] = heightMap[i][0]
heapq.heappush(min_height,(heightMap[i][n-1],i,n-1))
water[i][n-1] = heightMap[i][n-1]
self.ans = 0
# 计算位置(i,j)能接的雨水量
def cal_water(h,i,j):
if heightMap[i][j] >= h:
water[i][j] = heightMap[i][j]
else:
self.ans += h - heightMap[i][j] # 累加接雨水量
water[i][j] = h
heapq.heappush(min_height, (water[i][j],i,j))
while min_height:
h, i, j = heapq.heappop(min_height) # 取出堆顶元素
# 判断四周是否有未访问过的元素
if i > 0 and water[i-1][j] == -1:
cal_water(h,i-1,j)
if i < m-1 and water[i+1][j] == -1:
cal_water(h,i+1,j)
if j > 0 and water[i][j-1] == -1:
cal_water(h,i,j-1)
if j < n-1 and water[i][j+1] == -1:
cal_water(h,i,j+1)
return self.ans</pre>
</div>
</div>
</div>
</section>
<section class="explore-section">
<h2>Explore</h2>
<div class="accordion" id="exploreAccordion">
<div class="card">
<div class="card-header" id="exploreHeader1">
<span class="mb-0">
<button class="btn btn-link btn-block text-start collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#exploreCollapse1" aria-expanded="false" aria-controls="exploreCollapse1">
为什么在初始化时,只将矩阵的边界元素加入最小堆,而不是全部元素? <i class="fas fa-chevron-down float-end"></i>
</button>
</span>
</div>
<div id="exploreCollapse1" class="collapse" aria-labelledby="exploreHeader1" data-bs-parent="#exploreAccordion">
<div class="card-body">
<p>在解决接雨水的问题时,水位的最高可能性始于边缘,因为边缘没有其他阻挡可以阻止水流走。通过从边界开始,我们可以确保我们模拟的水流是从最低点开始,逐渐向内部蔓延。这种方法可以避免不必要的计算,并能更准确地反映水的流动和积累。此外,边界元素是确定水能到达的最低高度的关键,它们自然形成了问题的'围栏'。</p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="exploreHeader2">
<span class="mb-0">
<button class="btn btn-link btn-block text-start collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#exploreCollapse2" aria-expanded="false" aria-controls="exploreCollapse2">
在计算可以接的雨水量时,为什么要比较当前元素的高度与水位数组中的水位,而不是直接使用矩阵中的高度? <i class="fas fa-chevron-down float-end"></i>
</button>
</span>
</div>
<div id="exploreCollapse2" class="collapse" aria-labelledby="exploreHeader2" data-bs-parent="#exploreAccordion">
<div class="card-body">
<p>计算接雨水量时,需要考虑由于四周较高的障碍物可能造成的水位提升。如果仅使用原始矩阵中的高度,我们无法考虑到因周围更高的障碍物而在较低地方积累的水。水位数组中的水位代表了实际的水面高度,包括由于四周的堵塞而可能上升的水位。这种方法确保了每个位置的计算都基于最真实的水面情况,从而准确地模拟和计算积水量。</p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="exploreHeader3">
<span class="mb-0">
<button class="btn btn-link btn-block text-start collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#exploreCollapse3" aria-expanded="false" aria-controls="exploreCollapse3">
在从最小堆中取出元素后,更新四周元素的策略为何选择只更新未访问过的元素? <i class="fas fa-chevron-down float-end"></i>
</button>
</span>
</div>
<div id="exploreCollapse3" class="collapse" aria-labelledby="exploreHeader3" data-bs-parent="#exploreAccordion">
<div class="card-body">
<p>选择只更新未访问过的元素是为了优化算法的性能并避免重复计算。一旦一个元素的水位被计算并更新,就意味着它已经被考虑过,其水位是当前可能的最小水位。如果重新更新已访问过的元素,可能会导致不必要的重复计算和错误的水位计算。此外,使用最小堆的性质保证了我们总是从最低可能的水位开始扩散,确保整个计算过程的正确性和效率。</p>
</div>
</div>
</div>
</div>
</section>
<aside class="related-problems-section">
<h2>Related Problems</h2>
<div class="list-group">
<a href="/problem/trapping-rain-water" class="list-group-item list-group-item-action">
接雨水
</a>
</div>
</aside>
</main>
<footer class="mt-4 mb-3">
<div class="d-flex justify-content-between">
<a href="/problems" class="btn btn-secondary">返回题目列表</a>
</div>
</footer>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.0/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
fetchInitialCounts();
setupEventListeners();
});
function fetchInitialCounts() {
fetch('/api/vote_count/trapping-rain-water-ii')
.then(response => response.json())
.then(data => {
document.getElementById('like-count').textContent = data.likes;
document.getElementById('dislike-count').textContent = data.dislikes;
})
.catch(error => console.error('Error loading initial counts:', error));
}
function setupEventListeners() {
document.getElementById('like-button').addEventListener('click', function() {
updateVoteCounts('like');
});
document.getElementById('dislike-button').addEventListener('click', function() {
updateVoteCounts('dislike');
});
const copyButtons = document.querySelectorAll('.copy-btn');
copyButtons.forEach(btn => {
btn.addEventListener('click', function() {
copyCode(this);
});
});
}
function updateVoteCounts(voteType) {
const baseUrl = "/api/vote/trapping-rain-water-ii/PLACEHOLDER";
const url = baseUrl.replace('PLACEHOLDER', voteType);
fetch(url, { method: 'POST' })
.then(response => response.json())
.then(data => {
if (data.likes !== undefined) {
document.getElementById('like-count').textContent = data.likes;
}
if (data.dislikes !== undefined) {
document.getElementById('dislike-count').textContent = data.dislikes;
}
})
.catch(error => console.error('Error updating counts:', error));
}
function copyCode(button) {
const codeBlock = button.previousElementSibling;
const code = codeBlock.textContent;
navigator.clipboard.writeText(code).then(function() {
button.textContent = '已复制';
setTimeout(function() {
button.textContent = '复制代码';
}, 2000);
}, function(err) {
console.error('无法复制代码: ', err);
});
}
</script>
</body>
</html>
|
// 36. Crie uma classe chamada "Conta" com os atributos número da conta, saldo e titular da conta. Implemente um construtor para esta classe. Crie um método para verificar se a conta está em débito (saldo negativo) e outro para depositar dinheiro na conta. Crie objetos de contas e teste os métodos.
class Conta {
constructor(numeroConta, saldoInicial, titular) {
this.numeroConta = numeroConta
this.saldo = saldoInicial
this.titular = titular
}
verificarDebito() {
return this.saldo < 0
}
depositar(valor) {
this.saldo += valor
console.log(`Depósito de R$ ${valor.toFixed(2)} realizado na conta ${this.numeroConta}. Novo saldo: R$ ${this.saldo.toFixed(2)}.`)
}
}
const conta1 = new Conta("12345", 1000, "João Silva")
const conta2 = new Conta("67890", -500, "Maria Oliveira")
console.log(`${conta1.titular}, a conta ${conta1.numeroConta} está em débito? ${conta1.verificarDebito() ? 'Sim' : 'Não'}`)
console.log(`${conta2.titular}, a conta ${conta2.numeroConta} está em débito? ${conta2.verificarDebito() ? 'Sim' : 'Não'}`)
conta1.depositar(500)
conta2.depositar(200)
console.log(`${conta1.titular}, a conta ${conta1.numeroConta} está em débito? ${conta1.verificarDebito() ? 'Sim' : 'Não'}`)
console.log(`${conta2.titular}, a conta ${conta2.numeroConta} está em débito? ${conta2.verificarDebito() ? 'Sim' : 'Não'}`)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.