text
stringlengths 184
4.48M
|
---|
import math
import pygame as pg
from src.constants import WINDOW_SIZE
class Body:
def __init__(self, rect: pg.Rect, collidables: list = None):
self.is_jumping = False
self.on_ground = False
self.gravity = .35
self.friction = -.12
self.rect = rect
self.collidables = collidables or []
self.head_collision = None
self.right_collision = None
self.left_collision = None
self.collision_enabled = True
self.fall_off_map = False
self.position = pg.math.Vector2(self.rect.x, self.rect.y)
self.velocity = pg.math.Vector2(0, 0)
self.acceleration = pg.math.Vector2(0, self.gravity)
self.use_constant_velocity = False
self.use_constant_velocity_vertical = False
def update(self, dt: float):
self.horizontal_movement(dt)
self.vertical_movement(dt)
def horizontal_movement(self, dt: float):
if self.use_constant_velocity:
self.velocity.x = self.acceleration.x
else:
self.acceleration.x += self.velocity.x * self.friction
self.velocity.x += self.acceleration.x * dt
self.limit_velocity(4)
self.position.x += self.velocity.x * dt + (self.acceleration.x * .5) * (dt * dt)
self.rect.x = self.position.x
if self.collision_enabled:
self.check_collisions_x()
def vertical_movement(self, dt: float):
if self.use_constant_velocity_vertical:
self.velocity.y = self.acceleration.y
else:
self.velocity.y += self.acceleration.y * dt
if self.velocity.y > 7:
self.velocity.y = 7
self.position.y += self.velocity.y * dt + (self.acceleration.y * .5) * (dt * dt)
self.rect.bottom = self.position.y
if self.collision_enabled:
self.check_collisions_y()
def limit_velocity(self, max_vel: float):
self.velocity.x = max(-max_vel, min(self.velocity.x, max_vel))
if abs(self.velocity.x) < .01:
self.velocity.x = 0
def get_hits(self) -> list:
# keep only the closest tiles
tiles = [
i for i in self.collidables
if math.hypot(self.rect.x - self.rect.w / 2 - i.rect.x, self.rect.y - i.rect.y) < 80
]
# sort the tiles so the collision checks first the closest tile and not the first in list
tiles = sorted(self.collidables, key=lambda x: math.hypot(self.rect.x - x.rect.x, self.rect.y - x.rect.y))
for tile in tiles:
if self.rect.colliderect(tile):
yield tile
def check_collisions_x(self):
self.left_collision, self.right_collision = None, None
if self.position.x <= 0:
self.position.x = 0
self.rect.x = self.position.x
for tile in self.get_hits():
if self.velocity.x > 0:
self.position.x = tile.rect.left - self.rect.w
self.rect.x = self.position.x
self.right_collision = tile
if self.velocity.x < 0:
self.position.x = tile.rect.right
self.rect.x = self.position.x
self.left_collision = tile
def check_collisions_y(self):
self.head_collision = None
self.on_ground = False
self.rect.bottom += 1
self.fall_off_map = False
if self.position.y > WINDOW_SIZE[1] + self.rect.h and self.collision_enabled:
self.fall_off_map = True
if self.fall_off_map:
return
if self.position.y <= 0:
self.position.y = 0
self.rect.y = self.position.y
for tile in self.get_hits():
if self.velocity.y > 0:
self.on_ground = True
self.is_jumping = False
self.velocity.y = 0
self.position.y = tile.rect.top
self.rect.bottom = self.position.y
if self.velocity.y < 0:
self.velocity.y = 0
self.position.y = tile.rect.bottom + self.rect.h
self.rect.bottom = self.position.y
self.head_collision = tile
|
<div class="auth-wrapper">
<div class="auth-card card">
<form [formGroup]="resetPasswordForm" (submit)="resetPassword()">
<div class="card-body">
<h3 class="fw-bold text-center mb-4 pb-2">{{'resetPassword.title' | translate}}</h3>
<!-- <p class="text-center text-gray mb-4">
{{'resetPassword.sub_title' | translate}}
</p> -->
<div class="form-group">
<div class="position-relative">
<input type="{{passwordInputType}}" formControlName="password"
placeholder="{{'resetPassword.placeholders.newPass' | translate}}" class="form-control" />
<div class="input-group-append">
<span class="visible-password position-absolute" id="basic-addon1" *ngIf="passwordInputType == 'password'"
(click)="passwordInputType = 'text'">
<i class="fa fa-eye-slash" aria-hidden="true"></i>
</span>
<span class="visible-password position-absolute" id="basic-addon2" *ngIf="passwordInputType == 'text'"
(click)="passwordInputType = 'password'">
<i class="fa fa-eye" aria-hidden="true"></i>
</span>
</div>
</div>
<div *ngIf="f['password'].errors" class="invalid-feedback d-block">
<div *ngIf="isSubmit && f['password'].errors?.['required']">
{{'resetPassword.errors.required.newPass' | translate}} </div>
<!-- <div *ngIf="
f['password'].errors?.['minlength'] ||
f['password']?.hasError('pattern')
">
{{'resetPassword.errors.valid.newPass' | translate}}
</div> -->
<div *ngIf="f?.['password']?.errors?.['minlength']" class="">
<!-- <i class="fa fa-info-circle" aria-hidden="true"></i> -->
<span class="ps-1 me-1 text-danger" *ngIf="f?.['password']?.errors?.['minlength']">Your password should be
of atleast
8 digit long.</span>
</div>
</div>
</div>
<div class="form-group">
<div class="position-relative ">
<input type="{{confirmPasswordInputType}}" formControlName="confirm_password"
placeholder="{{'resetPassword.placeholders.confirmPass' | translate}}" class="form-control" />
<div class="input-group-append">
<span class="visible-password position-absolute" id="basic-addon1"
*ngIf="confirmPasswordInputType == 'password'" (click)="confirmPasswordInputType = 'text'">
<i class="fa fa-eye-slash" aria-hidden="true"></i>
</span>
<span class="visible-password position-absolute" id="basic-addon2"
*ngIf="confirmPasswordInputType == 'text'" (click)="confirmPasswordInputType = 'password'">
<i class="fa fa-eye" aria-hidden="true"></i>
</span>
</div>
</div>
<div *ngIf="f['confirm_password'].errors || mustMatch" class="invalid-feedback d-block">
<div *ngIf="isSubmit && f['confirm_password'].errors?.['required']">
{{'resetPassword.errors.required.confrmPass' | translate}}
</div>
<!-- <div *ngIf="mustMatch">
{{'resetPassword.errors.valid.confrmPass' | translate}}
</div> -->
<div *ngIf="f?.['confirm_password']?.errors?.['confirmedValidator']" class="text-danger">
{{'resetPassword.errors.valid.confrmPass' | translate}}
</div>
</div>
</div>
<div class="form-group text-center mt-5 mb-0">
<button type="submit" class="btn btn-primary w-100">{{'resetPassword.saveButton' | translate}}</button>
</div>
</div>
</form>
</div>
</div>
<!-- <auth-footer></auth-footer> -->
|
<script>
import axios from 'axios';
import { isJwtExpired } from 'jwt-check-expiration';
import bar from '@/components/Navbar.vue'
import foot from '@/components/Footer.vue'
export default {
name: "forget",
components: {
bar,
foot
},
data: () => ({
error: ""
}),
methods: {
submitForm() {
let form = new FormData(this.$refs.forgetForm);
axios.post("http://backend.rottencucumber.tk/api/auth/forget", form)
.then((res) => {
let data = res.data
if (data.success) {
this.$router.push({ name: 'new-password', params: { token: data.message } });
} else {
this.error = data.message
}
})
.catch((error) => {
this.error = "Something happen please try again."
});
}
},
beforeMount() {
let token = localStorage.getItem("access_token");
if (token != null && !isJwtExpired(token)) {
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;
this.$router.push({ name: 'home' })
} else {
localStorage.removeItem("access_token")
axios.defaults.headers.common['Authorization'] = null;
}
}
}
</script>
<template>
<bar />
<div class="modal">
<div class="modal-content">
<div class="auth-header">
<div class="auth-title h4">
<div class="title">Recovery Password</div>
</div>
</div>
<div class="auth-body modal-body">
<form class="content reset-form" v-on:submit.prevent="submitForm" ref="forgetForm">
<div class="hide-on-success">
<div class="form-group">
<i class="fa fa-envelope"></i>
<input type="email" name="email" class="form-control" required placeholder="Email">
</div>
<div class="form-error">
{{ error }}
</div>
<div class="form-group">
<button class="submit-btn button main__button " type="submit"
style="padding: 10px 50px; width: 100%;">SUBMIT</button>
</div>
</div>
</form>
</div>
<div class="auth-footer">
<RouterLink :to="{ name: 'login' }" title="Back to login">
<i class="fa fa-angle-right"></i>
Back to login
</RouterLink>
<RouterLink :to="{ name: 'signup' }">
<i class="fa fa-angle-right"></i>
Create an account
</RouterLink>
</div>
</div>
</div>
<foot />
</template>
<style scoped>
.modal {
align-content: center;
padding: 80px;
height: auto;
background-color: rgba(0, 0, 0, 0.2);
overflow: auto;
}
.modal-content {
position: relative;
margin: auto;
padding: 20px;
width: 90%;
max-width: 400px;
pointer-events: auto;
border-radius: 0.3rem;
outline: 0;
background-color: #DEECDE;
}
.auth-header {
border: none;
padding: 0 40px 0;
text-align: center;
position: relative;
}
.modal-body {
position: relative;
-ms-flex: 1 1 auto;
flex: 1 1 auto;
padding: 1rem;
}
.auth-footer {
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-ms-flex-align: center;
align-items: center;
-ms-flex-pack: end;
justify-content: space-between;
padding: 0.75rem;
border-top: 1px solid white;
border-bottom-right-radius: calc(0.3rem - 1px);
border-bottom-left-radius: calc(0.3rem - 1px);
}
.auth-header .auth-title {
width: 100%;
flex-direction: column;
display: flex;
}
.auth-header .title {
position: relative;
font-weight: 600;
font-size: 2rem;
margin-bottom: 20px;
text-align: center;
display: inline-block;
text-transform: uppercase;
color: #2A2C32;
}
.form-control {
display: block;
width: 100%;
height: 32px;
padding: 6px 30px;
font-size: 13px;
line-height: 1.42857;
color: #555;
background-color: #eee;
border: 1px solid #eee;
border-radius: 3px;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
}
.form-group {
position: relative;
margin-bottom: 15px;
}
input:not([type=checkbox]) {
background: white;
border: 1px solid #2A2C32;
}
.main__button {
background: #6FAC49;
border: none;
display: block;
padding: 10px 10px;
text-align: center;
font-weight: 700;
color: #fff !important;
cursor: pointer;
border-radius: 2px;
height: 40px;
position: relative;
}
i[class*="fa-"] {
display: inline-block;
width: 16px;
text-align: center;
}
.form-group i {
position: absolute;
text-align: center;
color: #2A2C32;
top: 8px;
left: 7px;
width: 12px;
height: 12px;
}
.form-error {
color: #BD1E1E;
}
.auth-footer a {
cursor: pointer;
color: #2A2C32;
text-decoration: none;
}
.auth-footer a:hover {
color: #4583C1;
transition: all 0.1s;
}
</style>
|
import type { Meta, StoryObj } from "@storybook/react";
import { INITIAL_BUILD_PAYLOAD } from "../buildSteps";
import {
buildStep,
completeStep,
initializeStep,
snapshotStep,
uploadStep,
verifyStep,
} from "../screens/VisualTests/mocks";
import { withFigmaDesign } from "../utils/withFigmaDesign";
import { BuildProgressLabel } from "./BuildProgressLabel";
const meta = {
component: BuildProgressLabel,
} satisfies Meta<typeof BuildProgressLabel>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Initialize: Story = {
args: {
localBuildProgress: {
...INITIAL_BUILD_PAYLOAD,
stepProgress: initializeStep,
},
},
parameters: withFigmaDesign(
"https://www.figma.com/file/GFEbCgCVDtbZhngULbw2gP/Visual-testing-in-Storybook?type=design&node-id=2892-73423&mode=design&t=gIM40WT0324ynPQD-4"
),
};
export const Build: Story = {
args: {
localBuildProgress: {
...Initialize.args.localBuildProgress,
buildProgressPercentage: 8,
currentStep: "build",
stepProgress: buildStep,
},
},
parameters: withFigmaDesign(
"https://www.figma.com/file/GFEbCgCVDtbZhngULbw2gP/Visual-testing-in-Storybook?type=design&node-id=2892-73453&mode=design&t=gIM40WT0324ynPQD-4"
),
};
export const Upload: Story = {
args: {
localBuildProgress: {
...Build.args.localBuildProgress,
buildProgressPercentage: 25,
currentStep: "upload",
stepProgress: uploadStep,
},
},
parameters: withFigmaDesign(
"https://www.figma.com/file/GFEbCgCVDtbZhngULbw2gP/Visual-testing-in-Storybook?type=design&node-id=2935-71430&mode=design&t=gIM40WT0324ynPQD-4"
),
};
export const Verify: Story = {
args: {
localBuildProgress: {
...Upload.args.localBuildProgress,
buildProgressPercentage: 50,
currentStep: "verify",
stepProgress: verifyStep,
},
},
parameters: withFigmaDesign(
"https://www.figma.com/file/GFEbCgCVDtbZhngULbw2gP/Visual-testing-in-Storybook?type=design&node-id=2935-72020&mode=design&t=gIM40WT0324ynPQD-4"
),
};
export const Snapshot: Story = {
args: {
localBuildProgress: {
...INITIAL_BUILD_PAYLOAD,
buildProgressPercentage: 75,
currentStep: "snapshot",
stepProgress: snapshotStep,
},
},
parameters: withFigmaDesign(
"https://www.figma.com/file/GFEbCgCVDtbZhngULbw2gP/Visual-testing-in-Storybook?type=design&node-id=2892-74603&mode=design&t=gIM40WT0324ynPQD-4"
),
};
export const Complete: Story = {
args: {
localBuildProgress: {
...INITIAL_BUILD_PAYLOAD,
currentStep: "complete",
buildProgressPercentage: 100,
stepProgress: completeStep,
},
},
parameters: withFigmaDesign(
"https://www.figma.com/file/GFEbCgCVDtbZhngULbw2gP/Visual-testing-in-Storybook?type=design&node-id=2892-74801&mode=design&t=gIM40WT0324ynPQD-4"
),
};
export const Error: Story = {
args: {
localBuildProgress: {
...INITIAL_BUILD_PAYLOAD,
currentStep: "error",
buildProgressPercentage: 30,
stepProgress: buildStep,
},
},
};
export const Aborted: Story = {
args: {
localBuildProgress: {
...INITIAL_BUILD_PAYLOAD,
currentStep: "aborted",
buildProgressPercentage: 50,
stepProgress: uploadStep,
},
},
};
|
import { Button } from "@relume_io/relume-ui";
import type { ButtonProps } from "@relume_io/relume-ui";
type Props = {
heading: string;
description: string;
buttons: ButtonProps[];
};
export type Cta7Props = React.ComponentPropsWithoutRef<"section"> & Partial<Props>;
export const Cta7 = (props: Cta7Props) => {
const { heading, description, buttons } = {
...Cta7Defaults,
...props,
} as Props;
return (
<section className="px-[5%] py-16 md:py-24 lg:py-28">
<div className="container grid w-full grid-cols-1 items-start justify-between gap-6 md:grid-cols-[1fr_max-content] md:gap-x-12 md:gap-y-8 lg:gap-x-20">
<div className="md:mr-12 lg:mr-0">
<div className="w-full max-w-lg">
<h2 className="mb-3 text-4xl font-bold leading-[1.2] md:mb-4 md:text-5xl lg:text-6xl">
{heading}
</h2>
<p className="md:text-md">{description}</p>
</div>
</div>
<div className="flex items-start justify-start gap-4">
{buttons.map((button, index) => (
<Button
key={index}
variant={button.variant}
size={button.size}
iconRight={button.iconRight}
iconLeft={button.iconLeft}
>
{button.title}
</Button>
))}
</div>
</div>
</section>
);
};
export const Cta7Defaults: Cta7Props = {
heading: "Get Your Tickets Now!",
description: "Experience the Event of a Lifetime.",
buttons: [{ title: "Buy Ticket" }],
};
Cta7.displayName = "Cta7";
|
package com.dama.cerbero.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.dama.cerbero.entities.MailTable;
import com.dama.cerbero.entities.Subscriber;
import com.dama.cerbero.entities.TransactionTable;
import com.dama.cerbero.entities.interfaces.MailRepository;
import com.dama.cerbero.entities.interfaces.SubscriberRepository;
import com.dama.cerbero.entities.interfaces.TransactionRepository;
import com.dama.cerbero.requests.Airdrop;
import com.dama.cerbero.requests.Transaction;
import com.dama.cerbero.requests.ConnectRequest;
import com.dama.cerbero.requests.SendEmailRequest;
import com.dama.cerbero.requests.Wallet;
import com.dama.cerbero.responses.Outcome;
import com.dama.cerbero.responses.SolanaResponse;
import com.google.gson.Gson;
@RestController
public class MainController {
private static final Logger log = LoggerFactory.getLogger(MainController.class);
private static final Runtime rt = Runtime.getRuntime();
@Value("${url.solana}")
String url;
@Autowired
SubscriberRepository userRepository;
@Autowired
TransactionRepository txRepository;
@Autowired
MailRepository mailRepository;
private static final String template = "Hello, %s!";
@GetMapping("/greeting")
public String greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format(template, name);
}
@CrossOrigin
@PostMapping(path = "/connect", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Outcome connect(@RequestBody ConnectRequest request) {
log.info("POST /connect");
try {
log.info("Wallet Adapter Name: " + request.getAdapter());
} catch (Exception e) {
log.error("Canìt parse body");
}
return new Outcome(true);
}
@CrossOrigin
@PostMapping(path = "/sendemail", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Outcome sendemail(@RequestBody SendEmailRequest request) {
log.info("POST /sendemail");
try {
String email = request.getEmail();
String subject = request.getSubject();
String message = request.getMessage();
log.info("Message From: " + email);
log.info("Message Subject: " + subject);
log.info("Message: " + request.getMessage());
try {
mailRepository.save(new MailTable(email, subject, message));
} catch (Exception e) {
log.error("Errore durante il salvataggio sul DB. Eccezione: ");
log.error(e.getMessage(), e.getCause());
return new Outcome("ERROR");
}
} catch (Exception e) {
log.error("Canìt parse body");
}
return new Outcome(true);
}
@CrossOrigin
@PostMapping(path = "/enrol", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Outcome enrol(@RequestBody Airdrop airdrop) {
log.info("POST /enrol");
try {
if (userRepository.count() < 1000) {
userRepository.save(new Subscriber(airdrop));
} else {
return new Outcome("POOL MAX SIZE REACHED");
}
} catch (Exception e) {
log.error("Exception occurred while trying to save customer " + airdrop);
log.debug(e.getMessage(), e.getCause());
if (e.getMessage().contains("Duplicate"))
return new Outcome("DUPLICATE");
return new Outcome(false);
}
log.info("Correctly saved customer " + airdrop);
return new Outcome(true);
}
@CrossOrigin
@PostMapping(path = "/check", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Outcome check(@RequestBody Wallet wallet) {
log.info("POST /check");
try {
List<Subscriber> subscribers = userRepository.findByAddress(wallet.getAddress());
if (subscribers.isEmpty()) {
if (userRepository.count() <= 1000) {
return new Outcome("CAN");
} else
return new Outcome("FU");
}
for (Subscriber s : subscribers) {
return new Outcome("WIN");
}
} catch (Exception e) {
log.error("Exception occurred while trying to get customer " + wallet);
log.debug(e.getMessage(), e.getCause());
return new Outcome("ERROR");
}
log.info("Correctly investigated customer " + wallet);
return new Outcome(true);
}
@CrossOrigin
@PostMapping(path = "/sendtransaction", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Outcome rpcSend(@RequestBody Transaction tx) {
log.info("POST /sendtransaction");
try {
JSONObject json = new JSONObject();
json.put("jsonrpc", "2.0");
json.put("id", 1);
json.put("method", "sendTransaction");
json.put("params", tx.getParams());
log.info(json.toString());
int run = 10;
HttpResponse<String> response = null;
while (run > 0) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-type", "application/json")
.header("Accept", "application/json")
.POST(BodyPublishers.ofString(json.toString()))
.build();
response = client.send(request, BodyHandlers.ofString());
log.info("Outcome: " + response.statusCode());
log.info(response.body());
if (response.body().contains("result")) {
run = 0;
} else {
run--;
TimeUnit.SECONDS.sleep(4);
}
}
SolanaResponse solanaResponse = new Gson().fromJson(response.body(), SolanaResponse.class);
log.info("Ho mappato la risposta di Solana");
try {
txRepository.save(new TransactionTable(tx, solanaResponse, "mainnet", ""));
} catch (Exception e) {
log.error("Errore durante il salvataggio sul DB. Eccezione: ");
log.error(e.getMessage(), e.getCause());
return new Outcome("ERROR");
}
} catch (Exception e) {
log.error("Eserrotto ");
log.debug(e.getMessage(), e.getCause());
return new Outcome("ERROR");
}
log.info("Done ");
return new Outcome(true);
}
@CrossOrigin
@PostMapping(path = "/sendtransactiondevnet", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Outcome devnetSend(@RequestBody Transaction tx) {
log.info("POST /sendtransactiondevnet");
try {
JSONObject json = new JSONObject();
json.put("jsonrpc", "2.0");
json.put("id", 1);
json.put("method", "sendTransaction");
json.put("params", tx.getParams());
log.info(json.toString());
int run = 10;
HttpResponse<String> response = null;
while (run > 0) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.devnet.solana.com"))
.header("Content-type", "application/json")
.header("Accept", "application/json")
.POST(BodyPublishers.ofString(json.toString()))
.build();
response = client.send(request, BodyHandlers.ofString());
log.info("Outcome: " + response.statusCode());
log.info(response.body());
if (response.body().contains("result")) {
run = 0;
} else {
run--;
TimeUnit.SECONDS.sleep(4);
}
}
SolanaResponse solanaResponse = new Gson().fromJson(response.body(), SolanaResponse.class);
log.info("Ho mappato la risposta di Solana");
try {
txRepository.save(new TransactionTable(tx, solanaResponse, "devnet", ""));
} catch (Exception e) {
log.error("Errore durante il salvataggio sul DB. Eccezione: ");
log.error(e.getMessage(), e.getCause());
return new Outcome("ERROR");
}
} catch (Exception e) {
log.error("Eserrotto ");
log.debug(e.getMessage(), e.getCause());
return new Outcome("ERROR");
}
log.info("Done ");
return new Outcome(true);
}
@CrossOrigin
@PostMapping(path = "/confirmtransaction", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Outcome rpcCheck(@RequestBody SolanaResponse tx) {
String response = "KO";
String command = "/home/solana/.local/share/solana/install/releases/stable-d0ed878d573c7f5391cd2cba20465407f63f11a8/solana-release/bin/solana confirm ";
log.info("POST /confirmtransactioj");
try {
Process proc = rt.exec(command + tx.getResult());
log.info("TX = "+tx.getResult());
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// Read the output from the command
String s = null;
try {
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
response= s;
log.info("RESPONSE = ["+s+"]");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Read any errors from the attempted command
try {
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
log.debug(e.getMessage(), e.getCause());
return new Outcome("ERROR");
}
log.info("Done ");
return new Outcome(response);
}
}
|
import React from 'react';
import styles from './Progress.module.scss';
import TrackProgress from '@/components/track/trackProgress/TrackProgress';
import { motion } from 'framer-motion';
import { usePlayerStore } from '@/stores/playerStore';
import { audio } from '@/components/track/tracklist/TrackList';
import { formatTime } from '@/utils';
const Progress = () => {
const currentTime = usePlayerStore((state) => state.currentTime);
const duration = usePlayerStore((state) => state.duration);
const setCurrentTime = usePlayerStore((state) => state.setCurrentTime);
const changeCurrentTime = (e: React.ChangeEvent<HTMLInputElement>): void => {
e.stopPropagation();
audio.currentTime = Number(e.target.value);
setCurrentTime(Number(e.target.value));
};
return (
<motion.div
className={styles.root}
drag={'y'}
dragConstraints={{
top: 0,
bottom: 0,
}}
dragElastic={0}
>
<div className={styles.root__currentTime}>{formatTime(currentTime)}</div>
<TrackProgress
left={currentTime}
right={duration}
onChange={changeCurrentTime}
/>
<div className={styles.root__duration}>{formatTime(duration)}</div>
<div className={styles.root__mobileTimes}>
<motion.div
animate={
(currentTime * 100) / duration < 12
? { translateY: '10px' }
: { translateY: 0 }
}
>
{formatTime(currentTime)}
</motion.div>
<motion.div
animate={
(currentTime * 100) / duration > 88
? { translateY: '10px' }
: { translateY: 0 }
}
>
{formatTime(duration)}
</motion.div>
</div>
</motion.div>
);
};
export default Progress;
|
<template>
<el-tabs @tab-click="changeTab" v-model="editableTabsValue" type="card" class="demo-tabs" closable @tab-remove="removeTab">
<el-tab-pane v-for="item in editableTabs" :key="item.path" :label="item.title" :name="item.path">
{{ item.content }}
</el-tab-pane>
</el-tabs>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { tabsType } from '@/store/type/tabsType'
import { useStore } from '@/store/index'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const store = useStore()
// 获取tabs数组
const editableTabs = computed(() => {
return store.getters['tabs/getTabs']
})
// 激活的tabs
const editableTabsValue = ref('')
const getActiceTab = () => {
editableTabsValue.value = route.path
}
// 添加tabs
const addTab = () => {
const { path, meta } = route
const tabs: tabsType = {
path: path,
title: meta.title as string
}
store.commit('tabs/updateTabArr', tabs)
}
watch(
() => route.path,
() => {
getActiceTab()
addTab()
}
)
// 移除tabs
const removeTab = (targetName: string) => {
if (targetName === '/dashboard') return
// console.log(targetName)
const tabs = editableTabs.value
let activeName = editableTabsValue.value
if (activeName === targetName) {
tabs.forEach((tab: tabsType, index: number) => {
if (tab.path === targetName) {
const nextTab = tabs[index + 1] || tabs[index - 1]
if (nextTab) {
activeName = nextTab.path
}
}
})
}
editableTabsValue.value = activeName
// store.getters['tabs/getTabs'] = tabs.filter((tab: tabsType) => tab.path !== targetName) ???????????????????????????????
store.state.tabs.tabsArr = tabs.filter((tab: tabsType) => tab.path !== targetName)
router.push({ path: activeName })
}
// 点击切换路由
const changeTab = (tab: any) => {
// console.log(tab)
const { props } = tab
// console.log(props)
router.push({ path: props.name })
}
// 解决页面刷新,tab重置的问题(对tabs进行缓存
const setTabs = () => {
// 解决登录不同权限的用户时,tabs栏缓存的是上个用户的tabs
if (route.path !== '/login') {
// 这里因为全局在window身上挂载了事件刷新,因此在我们页面跳转的时候(也为刷新,所以会在跳转后会再进行一次本地存储
window.addEventListener('beforeunload', () => {
localStorage.setItem('tabsView', JSON.stringify(editableTabs.value))
let token = sessionStorage.getItem('token')
localStorage.setItem('xx', token!)
})
const oldtabs = localStorage.getItem('tabsView')
if (localStorage.getItem('xx') == sessionStorage.getItem('token')) {
// 这里不建议直接操作仓库中的state,建议用mutations,多写一步
// 能读取到数据才执行赋值
// store.state.tabsArr = JSON.parse(oldtabs) ??????????????????????????????????????????????????????????????
// store.getters['getTabs'] = JSON.parse(oldtabs)
store.commit('tabs/changeTab', JSON.parse(oldtabs!))
}
}
}
onMounted(() => {
setTabs()
getActiceTab()
// addTab()
console.log(store)
})
</script>
<style scoped lang="scss">
:deep(.el-tabs__header) {
margin: 0px;
}
:deep(.el-tabs__item) {
height: 26px !important;
line-height: 26px !important;
text-align: center !important;
border: 1px solid #d8dce5 !important;
margin: 0px 3px !important;
color: #495060;
font-size: 12px !important;
padding: 0xp 10px !important;
}
:deep(.el-tabs__nav) {
border: none !important;
}
:deep(.is-active) {
border-bottom: 1px solid transparent !important;
border: 1px solid #42b983 !important;
background-color: #42b983 !important;
color: #fff !important;
}
:deep(.el-tabs__item:hover) {
color: #495060 !important;
}
:deep(.is-active:hover) {
color: #fff !important;
}
</style>
|
import { StarIcon } from "@heroicons/react/solid";
import Button from "./ui/Button";
import { useNavigate } from "react-router-dom";
function BookGrid({ image, title, author, price, rating }) {
const navigate = useNavigate();
const handleClickImage = () => {
navigate(`/book/${title.split(" ").join("-")}`);
};
const onClick = () => {
console.log("clicked");
};
const rate =
Math.round(rating) > rating ? Math.round(rating) : Math.floor(rating);
return (
<div className="flex justify-evenly flex-1 h-56 mb-4">
{/* <img
src={image}
className="shadow-slate-300 shadow-xl"
alt="book"
onClick={handleClickImage}
/> */}
<div className="flex flex-col justify-between py-4">
<div>
<div className="flex">
{Array.from({ length: Math.round(rating) }, (_, i) => (
<StarIcon color="orange" width={20} height={20} key={i} />
))}
{5 - rating >= 0 &&
Array.from({ length: 5 - rate }, (_, i) => (
<StarIcon color="gray" width={20} height={20} key={i} />
))}
</div>
<h4 className="text-lg">{title}</h4>
<p className="text-slate-400">{author}</p>
</div>
<div>
<h5 className="mb-4 font-semibold">${price}</h5>
<Button onClick={onClick}>Buy Now</Button>
</div>
</div>
</div>
);
}
export default BookGrid;
|
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import styled from "styled-components";
import { Link } from "react-router-dom";
import {motion} from "framer-motion"
function Searched() {
const [searchedRecipes, setSearchedRecipes] = useState([]);
const params = useParams();
const getSearched = async (name) => {
const data = await fetch(
`https://api.spoonacular.com/recipes/complexSearch?apiKey=${process.env.REACT_APP_API_KEY}&query=${name}`
);
const recipes = await data.json();
setSearchedRecipes(recipes.results);
};
useEffect(() => {
getSearched(params.search);
}, [params.search]);
return (
<Grid animate={{ opacity: 1 }} initial={{ opacity: 0 }} exit={{ opacity: 0 }} transition={{ duration: 0.5 }}>
{searchedRecipes.map((item) => (
<Card key={item.id}>
<Link to={`/recipe/${item.id}`}>
<img src={item.image} alt="" />
<h4>{item.title}</h4>
</Link>
</Card>
))}
</Grid>
);
}
const Grid = styled(motion.div)`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr));
grid-gap: 3rem;
margin-top: 4rem;
`;
const Card = styled.div`
img {
width: 100%;
border-radius: 2rem;
}
a {
text-decoration: none;
}
h4 {
text-align: center;
padding: 1rem;
}
`;
export default Searched;
|
import { Test, TestingModule } from '@nestjs/testing';
import { PropertyType } from '@prisma/client';
import { Filter } from 'src/interfaces/home';
import { PrismaService } from 'src/prisma/prisma.service';
import { HomeService } from './home.service';
const homes = [
{
id: 6,
address: 'C81, Al-Falah near Sea View Park',
city: 'Gwadar',
price: 4500000,
realtor_id: 5,
images: [
{
url: 'src_1',
},
],
numberOfBedrooms: 5,
numberOfBathrooms: 5,
listedDate: '2022-06-25T19:57:15.345Z',
landSize: 6.9,
typeOfProperty: PropertyType.COMMERCIAL,
},
];
describe('Home Service', () => {
let homeService: HomeService;
let prismaService: PrismaService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
HomeService,
{
provide: PrismaService,
useValue: {
home: {
findMany: jest.fn().mockReturnValue(homes),
},
},
},
],
}).compile();
homeService = module.get<HomeService>(HomeService);
prismaService = module.get<PrismaService>(PrismaService);
});
describe('getHomes', () => {
const filter: Filter = {
city: 'Karachi',
price: {
gte: 100000,
lte: 3000000,
},
propertyType: PropertyType.COMMERCIAL,
};
it('should called prisma, home.findMany with correct params', async () => {
const mockPrismaFindManyHomesFunc = jest.fn().mockReturnValue(homes);
jest
.spyOn(prismaService.home, 'findMany')
.mockImplementation(mockPrismaFindManyHomesFunc);
await homeService.getHomes(filter);
expect(mockPrismaFindManyHomesFunc).toBeCalledWith({
where: filter,
include: {
images: {
take: 1,
select: {
url: true,
},
},
},
});
});
});
});
|
@extends('layouts.app')
@section('content')
<div class="card card-body">
<div style="display: flex" class="mb-3">
<div style="flex: 1">
<h4 id="section1" class="mg-b-10">Edit Company</h4>
</div>
<div>
<a href="{{route('module.'.$moduleName.'.home')}}" class="btn btn-primary btn-icon">
<i data-feather="arrow-left"></i>
</a>
</div>
</div>
<form action="{{route('module.'.$moduleName.'.update')}}" method="post" enctype="multipart/form-data">
@csrf
<input type="hidden" name="_method" value="put" />
<input type="hidden" name="id" value="{{$data['id']}}" />
<div class="form-row">
<div class="form-group col-md-8">
<label for="inputEmail4">Company Name <span class="tx-danger">*</span></label>
<input type="text" name="name" value="{{$data['name']}}" required class="form-control" id="inputEmail4" placeholder="Please enter company name">
@error('name')
<div class="tx-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group {{!empty($data['logo']) ? 'col-md-3':'col-md-4'}}" id="image-field">
<label for="inputEmail4">Company Image</label>
<div class="custom-file">
<input type="file" accept="image/*" name="logo" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
@if(!empty($data['logo']))
<div class="form-group col-md-1 mt-md-3" id="image-box" >
<a data-fancybox="gallery" href="{{url($data['logo'] ?: '')}}"><img class="rounded " src="{{url($data['logo'] ?: '')}}" width="50" height="50"></a>
@php $deleteFun = "deleteFile(".$data["id"].",'".route('module.companies.deleteFile',[$data["id"],'logo'])."','".csrf_token()."','".$data['logo']."','logo')" @endphp
<a href="javascript:" onclick="{{$deleteFun}}"><i class="fas fa-trash center-form" style="color: red;" ></i></a>
</div>
@endif
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Phone</label>
<input type="number" name="phone" value="{{$data['phone']}}" class="form-control" id="inputEmail4" placeholder="Please enter phone number">
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Email</label>
<input type="email" name="email" value="{{$data['email']}}" class="form-control" id="inputEmail4" placeholder="Please enter email address">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" name="address" value="{{$data['address']}}" class="form-control" id="inputAddress" placeholder="1234 Main St">
</div>
<div class="form-group">
<label for="inputAddress">NTN</label>
<input type="text" name="ntn" value="{{$data['ntn']}}" class="form-control @error('ntn') is-invalid @enderror" id="inputAddress" placeholder="198786-1">
</div>
<div class="form-group">
<label for="inputAddress">Note</label>
<textarea name="note" class="form-control" cols="30" rows="10">{{$data['note']}}</textarea>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Start Date</label>
<input type="text" name="start_date"
class="form-control datepicker @error('start_date') is-invalid @enderror"
placeholder="Choose date" value="{{date('m/d/Y',strtotime($data['start_date']))}}"
autocomplete="off">
@error('start_date')
<div class="tx-danger">{{ $message }}</div>
@enderror
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">End Date</label>
<input type="text" name="end_date"
class="form-control datepicker @error('end_date') is-invalid @enderror"
placeholder="Choose date" value="{{date('m/d/Y',strtotime($data['end_date']))}}"
autocomplete="off">
@error('end_date')
<div class="tx-danger">{{ $message }}</div>
@enderror
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
<button type="reset" class="btn btn-light">Reset</button>
</form>
</div>
@endsection
|
/**
* Wraps a function with a timeout.
* If the function does not complete within the specified time, the promise will be rejected.
*
* @template Return - The return type of the wrapped function.
* @template Err - The error type that can be thrown by the wrapped function or the error callback.
* @param {(...args: any[]) => Return} fn - The function to be wrapped.
* @param {number} time - The timeout duration in milliseconds.
* @param {(...args: any[]) => Err} [errCb] - Optional error callback function to handle timeout errors.
* @returns {(...args: any[]) => Promise<Return>} - A wrapped function that returns a promise.
*/
const timeout = <Return, Err>(
fn: (...args: any[]) => Return,
time: number,
errCb?: (...args: any[]) => Err
): ((...args: any[]) => Promise<Return>) => {
return (...args: any[]) => {
return new Promise<any>((resolve, reject) => {
const timer = setTimeout(() => {
if (errCb) reject(errCb(...args));
else {
reject(new Error("Function timed out"));
}
}, time);
// Wrap fn call in Promise.resolve to handle both sync and async functions
Promise.resolve(fn(...args))
.then((result: Return) => {
clearTimeout(timer);
resolve(result);
})
.catch((err: Err) => {
clearTimeout(timer);
reject(err);
});
});
};
};
export default timeout;
|
from textnode import TextNode
import re
from htmlnode import LeafNode, text_node_to_html_node, ParentNode
block_type_paragraph = "paragraph"
block_type_heading = "heading"
block_type_code = "code"
block_type_quote = "quote"
block_type_unordered_list = "unordered list"
block_type_ordered_list = "ordered list"
def split_nodes_delimiter(old_nodes, delimiter, text_type):
new_list = []
for node in old_nodes:
if isinstance(node, TextNode):
parts = node.text.split(delimiter)
for i, part in enumerate(parts):
if i % 2 == 0:
new_list.append(TextNode(part, node.text_type))
else:
new_list.append(TextNode(part, text_type))
else:
new_list.append(node)
return new_list
def extract_markdown_images(text):
matches = re.findall(r"!\[(.*?)\]\((.*?)\)", text)
return matches
def extract_markdown_links(text):
matches = re.findall(r"\[(.*?)\]\((.*?)\)", text)
return matches
def split_nodes_image(old_nodes):
new_nodes = []
for old_node in old_nodes:
if old_node.text_type != "text":
new_nodes.append(old_node)
continue
original_text = old_node.text
images = extract_markdown_images(original_text)
if len(images) == 0:
new_nodes.append(old_node)
continue
for image in images:
sections = original_text.split(f"![{image[0]}]({image[1]})", 1)
if len(sections) != 2:
raise ValueError("Invalid markdown, image section not closed")
if sections[0] != "":
new_nodes.append(TextNode(sections[0], "text"))
new_nodes.append(
TextNode(
image[0],
"image",
image[1],
)
)
original_text = sections[1]
if original_text != "":
new_nodes.append(TextNode(original_text, "text"))
return new_nodes
def split_nodes_link(old_nodes):
new_nodes = []
for old_node in old_nodes:
if old_node.text_type != "text":
new_nodes.append(old_node)
continue
original_text = old_node.text
links = extract_markdown_links(original_text)
if len(links) == 0:
new_nodes.append(old_node)
continue
for link in links:
sections = original_text.split(f"[{link[0]}]({link[1]})", 1)
if len(sections) != 2:
raise ValueError("Invalid markdown, link section not closed")
if sections[0] != "":
new_nodes.append(TextNode(sections[0], "text"))
new_nodes.append(TextNode(link[0], "link", link[1]))
original_text = sections[1]
if original_text != "":
new_nodes.append(TextNode(original_text, "text"))
return new_nodes
def text_to_textnodes(text):
nodes = [TextNode(text, "text")]
nodes = split_nodes_delimiter(nodes, "**", "bold")
nodes = split_nodes_delimiter(nodes, "*", "italic")
nodes = split_nodes_delimiter(nodes, "`", "code")
nodes = split_nodes_image(nodes)
nodes = split_nodes_link(nodes)
return nodes
def markdown_to_blocks(markdown):
raw_blocks = markdown.split("\n\n")
raw_blocks = [block.strip() for block in raw_blocks if block.strip()]
raw_blocks = ['\n'.join(line.lstrip() for line in block.split('\n')) for block in raw_blocks]
return raw_blocks
def block_to_block_type(block):
if block.startswith("#"):
return block_type_heading
if block.startswith("```") and block.endswith("```"):
return block_type_code
if all(line.startswith(">") for line in block.split("\n")):
return block_type_quote
if all(line.startswith(("* ", "- ")) for line in block.split("\n")):
return block_type_unordered_list
if all(line.startswith(f"{i}. ") for i, line in enumerate(block.split("\n"), 1)):
return block_type_ordered_list
return block_type_paragraph
def markdown_to_html_node(markdown):
blocks = markdown_to_blocks(markdown)
children = []
for block in blocks:
html_node = block_to_html_node(block)
children.append(html_node)
return ParentNode("div", children, None)
def text_to_children(text):
text_nodes = text_to_textnodes(text)
children = []
for text_node in text_nodes:
html_node = text_node_to_html_node(text_node)
children.append(html_node)
return children
def paragraph_to_html_node(block):
lines = block.split("\n")
paragraph = " ".join(lines)
children = text_to_children(paragraph)
return ParentNode("p", children)
def heading_to_html_node(block):
level = 0
for char in block:
if char == "#":
level += 1
else:
break
if level + 1 >= len(block):
raise ValueError(f"Invalid heading level: {level}")
text = block[level + 1:]
children = text_to_children(text)
return ParentNode(f"h{level}", children)
def code_to_html_node(block):
if not block.startswith("```") or not block.endswith("```"):
raise ValueError("Invalid code block")
text = block[4:-3]
children = text_to_children(text)
code = ParentNode("code", children)
return ParentNode("pre", [code])
def olist_to_html_node(block):
items = block.split("\n")
html_items = []
for item in items:
text = item[3:]
children = text_to_children(text)
html_items.append(ParentNode("li", children))
return ParentNode("ol", html_items)
def ulist_to_html_node(block):
items = block.split("\n")
html_items = []
for item in items:
text = item[2:]
children = text_to_children(text)
html_items.append(ParentNode("li", children))
return ParentNode("ul", html_items)
def quote_to_html_node(block):
lines = block.split("\n")
new_lines = []
for line in lines:
if not line.startswith(">"):
raise ValueError("not a quote")
new_lines.append(line.lstrip(">").strip())
content = " ".join(new_lines)
children = text_to_children(content)
return ParentNode("blockquote", children)
def block_to_html_node(block):
block_type = block_to_block_type(block)
if block_type == block_type_paragraph:
return paragraph_to_html_node(block)
if block_type == block_type_heading:
return heading_to_html_node(block)
if block_type == block_type_code:
return code_to_html_node(block)
if block_type == block_type_ordered_list:
return olist_to_html_node(block)
if block_type == block_type_unordered_list:
return ulist_to_html_node(block)
if block_type == block_type_quote:
return quote_to_html_node(block)
raise ValueError("Invalid block type")
|
import React, { useState, useEffect } from "react";
export default function Alert(props) {
const [showAlert, setShowAlert] = useState(true);
useEffect(() => {
const timeout = setTimeout(() => {
setShowAlert(false);
}, 2000);
// Clear the timeout when the component unmounts
return () => clearTimeout(timeout);
}, []);
return (
showAlert && (
<div className={`alert alert-${props.type} text-center fw-semibold`} role="alert">
{props.message}
</div>
)
);
}
|
import {useState} from 'react';
import './styles/AddPage.css';
import MovieItem from './MovieItem'
function AddPage(props) {
const [data, setData] = useState({
title: '',
img: '',
content: ''
});
const add = async () => {
const messageBox = document.getElementById('addTitle');
messageBox.innerText = "Adding...";
if(data.title.trim() === '' ||
data.content.trim() === ''){
messageBox.innerText = "Name and Description has to be filled";
return;
}
try{
await fetch("https://pr-movies.herokuapp.com/api/movies", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
})
messageBox.innerText = "Added succesfully";
}
catch(error){
messageBox.innerText = "Server error";
console.log(error);
}
}
return (
<div className='addContainer'>
<div className="addBox">
<div className="addForm">
<h3 id='addTitle'>Add a new movie</h3>
<input
value={data.title}
id='inputTitle'
placeholder="Name"
onChange={(event) =>{
setData({title:event.target.value,
image: data.image,
content: data.content});
}} />
<input
value={data.image}
id='inputImage'
placeholder="Image link"
onChange={(event) =>{
setData({title: data.title,
image: event.target.value,
content: data.content});
}} />
<textarea
id='inputContent'
value={data.content}
placeholder="Description"
onChange={(event) =>{
setData({title: data.title,
image: data.image,
content: event.target.value});
}} ></textarea>
<button onClick={add}>Add</button>
</div>
<div className="addPreview">
<MovieItem data={data} />
</div>
</div>
</div>
);
}
export default AddPage;
|
<!DOCTYPE HTML>
<html>
<head>
<title>Algorithme - Saison 6 - Exo 2</title>
<?php include "../commun/head.html" ?>
<script src="../js/saison6.js"></script>
</head>
<body>
<div id="page">
<!--header start -->
<header>
<?php include "../commun/header.html" ?>
</header>
<!--header end-->
<!--nav start -->
<nav>
<?php include "../commun/nav.html" ?>
</nav>
<!--nav end-->
<!--section start -->
<section>
<div>
<h2>Saison 6 - Exercice 2</h2>
<h3>Enoncé</h3>
<p class="p_blue">« Ecrire un algorithme qui déclare et remplisse un tableau contenant les six voyelles de l’alphabet latin. »</p>
</div>
<div>
<h3>PSEUDO-CODE</h3>
<textarea class="txt_pseudocode">
Variables Tableau Tab(6) en string
Début
Tab(0) <- a
Tab(1) <- e
Tab(2) <- i
Tab(3) <- o
Tab(4) <- u
Tab(5) <- y
Ecrire tab()
Fin
</textarea>
</div>
<div>
<p>
<button class="btn_green" onClick="showCode('div_jsform', 'btn_jsform')">CODE JavaScript VIA Formulaire</button>
<button class="btn_pink" onClick="showCode('div_jquery', 'btn_jquery')">CODE JQuery</button>
<button class="btn_black" onClick="showCode('div_php', 'btn_php')">CODE PHP</button>
</p>
<div id="div_jsform">
<textarea class="tarea_green">
function Exo_6_2_jsform()
{
let tab = new Array(6);
tab [0]="a";
tab [1]="e";
tab [2]="i";
tab [3]="o";
tab [4]="u";
tab [5]="y";
document.getElementById("sp_resultat_code").innerHTML = tab;
}
</textarea>
</div>
<div id="div_jquery">
<textarea class="tarea_pink">
function Exo_6_2_jquery()
{
var tab = new Array(6);
tab [0]="a";
tab [1]="e";
tab [2]="i";
tab [3]="o";
tab [4]="u";
tab [5]="y";
$("#sp_resultat_code").html(tab);
}
</textarea>
</div>
<div id="div_php">
<textarea class="tarea_black">
$sMessage= "";
$tab = array(6);
$i = 0;
if (isset($_POST["btn_php"]))
{
$tab [0]="a";
$tab [1]="e";
$tab [2]="i";
$tab [3]="o";
$tab [4]="u";
$tab [5]="y";
$sMessage = $tab;
}
require "exo_2.html";
</textarea>
</div>
</div>
<div id="div_form_resultat">
<div class="div_formulaire">
<!-- <p>
<button class="btn_grey" onClick="Saisie_prompt_exo_10(); return false;">Saisie des prix</button>
</p> -->
<form action="exo_2.php" method="POST" name="formPHP">
<!-- <p>Saisissez les prix des articles.</br>
Pour arrêter la saisie taper 0.</p>
<div id="input"> </div>
<div id="Total"> </div>
<div id="Payement"> </div>
<p> -->
<button class="btn_green" id="btn_jsform" onClick="Exo_6_2_jsform(); return false;">EXEC JavaScript VIA Formulaire</button>
<button class="btn_pink" id="btn_jquery" onClick="Exo_6_2_jquery(); return false;">EXEC JQuery</button>
<button class="btn_black" name="btn_php" id="btn_php" >EXEC PHP</button>
</p>
</form>
</div>
<div class="div_resultat">
<p>Ici mon résultat</p>
<span id="sp_resultat_code">
</span>
<span>
<?php
echo '<pre>';
print_r($sMessage);
echo '</pre>'
?>
</div>
</div>
</section>
<!--section end-->
<!--footer start-->
<footer>
<?php include "../commun/footer.html" ?>
</footer>
<!--footer end-->
</div>
</body>
</html>
|
//
// LoadingButton.swift
// wheels_Andrew
//
// Created by Andrew on 12.08.21.
//
import Foundation
import UIKit
import TinyConstraints
class LoadingButton: UIButton {
private var originalButtonText: String?
var activityIndicator: UIActivityIndicatorView!
func showLoading() {
originalButtonText = self.titleLabel?.text
self.setTitle("", for: .normal)
if activityIndicator == nil {
activityIndicator = createActivityIndicator()
}
showSpinning()
}
func hideLoading() {
self.setTitle(originalButtonText, for: .normal)
activityIndicator.stopAnimating()
}
private func createActivityIndicator() -> UIActivityIndicatorView {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.color = .systemGray
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.activityIndicator = activityIndicator
self.addSubview(activityIndicator)
centerActivityIndicatorInButton()
return activityIndicator
}
private func showSpinning() {
activityIndicator.startAnimating()
}
private func centerActivityIndicatorInButton() {
activityIndicator.horizontalToSuperview()
activityIndicator.verticalToSuperview()
}
}
|
最短路径算法是图论中的经典问题之一,用于寻找图中两个顶点之间的最短路径。常见的最短路径算法包括:
1.Dijkstra算法:用于解决单源最短路径问题,即从图中的一个顶点出发,求解到其他所有顶点的最短路径。Dijkstra算法采用贪心策略,逐步确定从起始顶点到其他顶点的最短路径,确保每次迭代都选择距离起始顶点最近的未访问顶点,并通过更新距离数组来实现。
在这个示例中,我们定义了一个DijkstraAlgorithm类,其中包含了实现Dijkstra算法的方法dijkstra。该方法接受一个加权邻接矩阵和源节点的索引,并返回一个包含从源节点到每个节点的最短距离的数组。然后,在main方法中,我们创建了一个示例图,并使用源节点0调用dijkstra方法来计算最短路径。
2.Bellman-Ford算法:用于解决单源最短路径问题,与Dijkstra算法不同的是,Bellman-Ford算法可以处理带有负权边的图。它通过对所有边进行松弛操作,多次迭代更新距离数组,直到所有边都被松弛。如果在进行V-1次迭代后仍然存在可以松弛的边,则说明图中存在负权环。
在这个示例中,我们定义了一个BellmanFordAlgorithm类,其中包含了实现Bellman-Ford算法的方法bellmanFord。该方法接受一个加权邻接矩阵和源节点的索引,并返回一个包含从源节点到每个节点的最短距离的数组。然后,在main方法中,我们创建了一个示例图,并使用源节点0调用bellmanFord方法来计算最短路径。
3.Floyd-Warshall算法:用于解决全源最短路径问题,即求解图中任意两个顶点之间的最短路径。Floyd-Warshall算法采用动态规划的思想,通过一个二维数组来记录任意两个顶点之间的最短路径长度,并通过三重循环逐步更新最短路径。
---
在这个示例中,
我们定义了一个FloydWarshallAlgorithm类,其中包含了实现Floyd-Warshall算法的方法floydWarshall。
该方法接受一个加权邻接矩阵,并返回一个包含从每个节点到每个节点的最短距离的二维数组。
然后,在main方法中,我们创建了一个示例图,并使用floydWarshall方法来计算所有节点之间的最短路径。
|
#ifndef SHELL_H
#define SHELL_H
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <limits.h>
#include <fcntl.h>
#include <errno.h>
/**
*struct list_s - singly linked list
*@str: string - (malloc'ed string)
*@len: length of the string
*@next: points to the next node
*
*Description: singly linked list node structure
*/
typedef struct list_s
{
char *str;
unsigned int len;
struct list_s *next;
} list_t;
/**
*struct built_in_command
*
*This structure is used to store information about built-in commands commonly
*found in a shell environment. It associates the command's name with its
*absolute file path on the system.
*
*@command: The name of the built-in command, e.g., "cp" for the copy command.
*@path: The absolute file path to the executable for the built-in command.
*/
typedef struct built_in_command
{
char *command;
void (*func)(char **array, size_t size, char **env __attribute__((unused)));
} built_in_command;
void exit_command(char **arr, size_t s, char **env __attribute__((unused)));
void env_command(char **arr, size_t s, char **env __attribute__((unused)));
void (*ex_builtin(char *cmd))(char **, size_t, char **);
int is_builtin(char *cmd);
void intractive_mode(int is_intractive, char **environ);
void print_env(char **environ);
int _strlen(char *str);
int _strcmp(char *str, char *s);
char *_strdup(char *c);
char *_strcat(char *dest, char *src);
char *_strcpy(char *dest, char *src);
void print_prompt(int is_intractive);
void free_list(list_t *head);
char **linked_list_to_array(list_t *head, size_t *size);
void free_array(char **array, size_t size);
size_t list_len(const list_t *h);
list_t *add_node_end(list_t **head, const char *str);
list_t *get_command(char *lineptr, list_t *head, ssize_t *flag);
void non_intractive_mode(const char *filename);
char *_getenv(const char *name, char **environ, int *offset);
char *_path(char *cmd, char **environ);
#endif
|
import { View, Text, StyleSheet, ScrollView } from 'react-native';
import React, { useState, useEffect } from 'react';
import ParkingCardComponent from './ParkingCardComponent';
const ParkingListComponent = () => {
const [inactiveSessions, setInactiveSessions] = useState([]);
const [parkingSpot, setParkingSpot] = useState({});
const fetchParkingSpotData = async () => {
try {
const response = await fetch('http://20.2.80.190:3000/api/create-park/641ddd6ced181dc7fff71d0a'); // Replace the URL and endpoint with your own
const data = await response.json();
setParkingSpot(data);
} catch (error) {
console.error('Error fetching parking spot data:', error);
}
};
useEffect(() => {
fetchParkingSpotData();
}, []);
const fetchInactiveSessions = async () => {
try {
const response = await fetch('http://20.2.80.190:3000/api/bookings/inactive-sessions'); // Replace the URL and endpoint with your own
const data = await response.json();
setInactiveSessions(data);
} catch (error) {
console.error('Error fetching inactive sessions data:', error);
}
};
useEffect(() => {
fetchInactiveSessions();
}, []);
function formatMongoDBTime(timestamp) {
const date = new Date(timestamp);
const hours = date.getHours();
const minutes = date.getMinutes();
const formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
return formattedTime;
}
function formatMongoDBDate(timestamp) {
const date = new Date(timestamp);
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
return formattedDate;
}
return (
<View style={styles.ParkingListContainer}>
<ScrollView
style={{ height: '70%' }}
contentContainerStyle={{
flexGrow: 1,
paddingVertical: 15,
}}
verticle
showsVerticalScrollIndicator={false}
>
{inactiveSessions.map((session) => (
<ParkingCardComponent
key={session._id}
title={parkingSpot.name}
location={parkingSpot.location} // Assuming the location is in the session object
startedTime={formatMongoDBTime(session.startTime)}
endedTime={formatMongoDBTime(session.endTime)}
date={formatMongoDBDate(session.startTime)}
/>
))}
</ScrollView>
</View>
);
};
const styles = StyleSheet.create({
ParkingListContainer: {
flex: 2,
alignItems: 'center',
height: '100%',
paddingTop: 20,
backgroundColor: '#E3D33C',
borderTopLeftRadius: 45,
borderTopRightRadius: 45,
},
parkingText: {
color: 'black',
fontSize: 25,
fontWeight: 700,
},
});
export default ParkingListComponent;
|
package com.twitter.config
import com.amazonaws.auth.AWSStaticCredentialsProvider
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.client.builder.AwsClientBuilder
import com.amazonaws.regions.Regions
import com.amazonaws.services.sqs.AmazonSQSAsync
import com.amazonaws.services.sqs.AmazonSQSAsyncClientBuilder
import io.awspring.cloud.messaging.config.QueueMessageHandlerFactory
import io.awspring.cloud.messaging.core.QueueMessagingTemplate
import io.awspring.cloud.messaging.listener.QueueMessageHandler
import io.awspring.cloud.messaging.listener.SimpleMessageListenerContainer
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.context.annotation.Profile
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
@Configuration
@Profile("!local")
class SQSConfig {
@Value("\${cloud.aws.accessKey}")
private var accessKey: String? = null
@Value("\${cloud.aws.secretKey}")
private var secretKey: String? = null
@Bean
@Primary
@Order(Ordered.HIGHEST_PRECEDENCE)
fun amazonSQSAsync(): AmazonSQSAsync? {
log.info("Config AWS SQS - URL: {} Region: {}", accessKey, secretKey) // TODO: Remove it
return AmazonSQSAsyncClientBuilder.standard().withRegion(Regions.US_WEST_1)
.withCredentials(AWSStaticCredentialsProvider(BasicAWSCredentials(accessKey, secretKey))).build()
}
@Bean
fun simpleMessageListenerContainer(
amazonSQSAsync: AmazonSQSAsync?,
queueMessageHandler: QueueMessageHandler?
): SimpleMessageListenerContainer? {
val simpleMessageListenerContainer = SimpleMessageListenerContainer()
simpleMessageListenerContainer.setAmazonSqs(amazonSQSAsync)
simpleMessageListenerContainer.setMessageHandler(queueMessageHandler)
simpleMessageListenerContainer.setMaxNumberOfMessages(10)
return simpleMessageListenerContainer
}
@Bean
fun queueMessageHandler(amazonSQSAsync: AmazonSQSAsync?): QueueMessageHandler? {
val queueMessageHandlerFactory = QueueMessageHandlerFactory()
queueMessageHandlerFactory.setAmazonSqs(amazonSQSAsync)
return queueMessageHandlerFactory.createQueueMessageHandler()
}
@Bean
fun queueMessagingTemplate(): QueueMessagingTemplate? {
return QueueMessagingTemplate(amazonSQSAsync())
}
companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
}
}
|
package com.example.android.popularmovies.ui;
import android.Manifest;
import android.app.DownloadManager;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.popularmovies.utils.AppExecutors;
import com.example.android.popularmovies.loader.DetailLoader;
import com.example.android.popularmovies.R;
import com.example.android.popularmovies.model.Review;
import com.example.android.popularmovies.adapter.ReviewAdapter;
import com.example.android.popularmovies.adapter.TrailerAdapter;
import com.example.android.popularmovies.database.AppDatabase;
import com.example.android.popularmovies.model.Movie;
import com.example.android.popularmovies.databinding.FragmentMovieDetailBinding;
import com.example.android.popularmovies.viewmodels.DetailMovieViewModel;
import com.example.android.popularmovies.viewmodels.DetailMovieViewModelFactory;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.example.android.popularmovies.ui.MainFragment.API_KEY;
import static com.example.android.popularmovies.ui.MainFragment.BASE_QUERY_URL;
import static com.example.android.popularmovies.ui.MainFragment.LOG_TAG;
public class DetailFragment extends Fragment implements
android.support.v4.app.LoaderManager.LoaderCallbacks<List<Review>>,
TrailerAdapter.ListItemClickListener {
private static final String SAVED_ID_KEY = "SAVED_MOVIE";
private FragmentMovieDetailBinding mBinding;
private static final int REVIEW_LOADER_ID = 2;
private static final int TRAILER_LOADER_ID = 3;
private static final int IMAGE_LOADER_ID = 4;
private static final int MY_PERMISSIONS_REQUEST = 22;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String IMAGES_DIR = "/my_images/";
private ReviewAdapter mAdapter;
private TrailerAdapter tAdapter;
private TextView reviewLabel, trailerLabel;
private Uri pictureUri;
private int targetW, targetH;
private String coverImageUri, posterImageUri;
private List<Movie> imagesUrl;
private int movieId = 0;
private Movie myMovie;
private AppDatabase mDb;
private Boolean isSortedByFavoriteMovie = false;
private Movie movieOnDb;
public DetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mDb = AppDatabase.getInstance(getActivity().getApplicationContext());
// If true, we're in tablet mode
if (getArguments() != null) {
myMovie = (Movie) getArguments()
.getParcelable("Movie");
movieId = getArguments()
.getInt("FavoriteMovieId");
}
if (movieId == 0){
Intent intent = getActivity().getIntent();
movieId = intent.getIntExtra("favoriteMovieId", 0);
}
if (savedInstanceState != null && savedInstanceState.containsKey(SAVED_ID_KEY)) {
movieId = savedInstanceState.getInt(SAVED_ID_KEY, 0);
}
if (movieId != 0) {
isSortedByFavoriteMovie = true;
checkMovieInDatabase(movieId);
}
requestPermissions();
}
public void requestPermissions() {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mBinding = DataBindingUtil.inflate(
inflater, R.layout.fragment_movie_detail, container, false);
View rootView = mBinding.getRoot();
if (!isOnline()) {
mBinding.fragmentMovieLayout.setVisibility(View.INVISIBLE);
mBinding.emptyDetails.setText(R.string.no_internet);
}
mBinding.fragmentMovieLayout.setVisibility(View.INVISIBLE);
if (myMovie == null) {
Intent intent = getActivity().getIntent();
myMovie = intent.getParcelableExtra("Movie");
}
if (myMovie != null) {
loadDetailsViews();
isSortedByFavoriteMovie = false;
reviewLabel = (TextView) rootView.findViewById(R.id.reviewsLabel);
reviewLabel.setVisibility(View.GONE);
trailerLabel = (TextView) rootView.findViewById(R.id.trailer_label);
trailerLabel.setVisibility(View.GONE);
// RecylerView to show user reviews
RecyclerView reviewsRV = (RecyclerView) rootView.findViewById(R.id.rv_reviews);
reviewsRV.setLayoutManager(new LinearLayoutManager(getActivity()));
reviewsRV.setHasFixedSize(true);
mAdapter = new ReviewAdapter(getActivity(), new ArrayList<Review>());
reviewsRV.setAdapter(mAdapter);
// RecylerView to show trailers
RecyclerView trailersRV = (RecyclerView) rootView.findViewById(R.id.rv_trailers);
LinearLayoutManager horizontalLayoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
trailersRV.setLayoutManager(horizontalLayoutManager);
reviewsRV.setHasFixedSize(true);
tAdapter = new TrailerAdapter(getActivity(), new ArrayList<Movie>(), this);
trailersRV.setAdapter(tAdapter);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(TRAILER_LOADER_ID, null, this);
loaderManager.initLoader(REVIEW_LOADER_ID, null, this);
loaderManager.initLoader(IMAGE_LOADER_ID, null, this);
mBinding.emptyDetails.setVisibility(View.GONE);
mBinding.fragmentMovieLayout.setVisibility(View.VISIBLE);
checkMovieInDatabase(myMovie.getId());
}
//Enable HomeAsUpEnable only if we're not on a tablet.
RecyclerView movieRecycler = (RecyclerView) getActivity().findViewById(R.id.rv_movies);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null && movieRecycler == null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
mBinding.favoriteBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
if (myMovie.getPosterImageUri() == null && movieOnDb==null) {
saveFavoriteMovie();
}
} else {
removeFavoriteMovie();
}
}
});
return rootView;
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
private void populateUI(Movie movie) {
if (movie == null) {
return;
}
Uri coverUri = Uri.parse(movie.getCoverImageUri());
Uri posterUri = Uri.parse(movie.getPosterImageUri());
WindowManager wm = (WindowManager) getView().getContext().getSystemService(Context.WINDOW_SERVICE);
Display screen = wm.getDefaultDisplay();
targetH = screen.getHeight();
targetW = screen.getWidth();
mBinding.movieDetailImage.setImageBitmap(getBitmapFromUri(coverUri));
mBinding.posterDetail.setImageBitmap(getBitmapFromUri(posterUri));
mBinding.titleInfo.setText(movie.getTitle());
mBinding.synopsisInfo.setText(movie.getOverview());
mBinding.ratingInfo.setText(movie.getVoteAverage().toString());
mBinding.releaseDateInfo.setText(movie.getReleaseDate());
mBinding.favoriteBtn.setChecked(true);
mBinding.trailerInclude.trailerLabel.setVisibility(View.GONE);
mBinding.trailerInclude.rvTrailers.setVisibility(View.GONE);
mBinding.reviewLayout.reviewsLabel.setVisibility(View.GONE);
mBinding.reviewLayout.rvReviews.setVisibility(View.GONE);
mBinding.emptyDetails.setVisibility(View.GONE);
mBinding.fragmentMovieLayout.setVisibility(View.VISIBLE);
}
private void saveFavoriteMovie() {
Integer id = myMovie.getId();
String title = myMovie.getTitle();
String overview = myMovie.getOverview();
Double voteAverage = myMovie.getVoteAverage();
String releaseDate = myMovie.getReleaseDate();
if (imagesUrl != null) {
String coverImageUrl = imagesUrl.get(0).getCoverImageURL();
downloadFile(coverImageUrl);
coverImageUri = pictureUri.toString();
} else {
coverImageUri = "null";
}
if (myMovie.getPosterThumbnail() != null) {
Toast.makeText(getActivity(), getString(R.string.adding_favorite_movie), Toast.LENGTH_SHORT).show();
downloadFile(myMovie.getPosterThumbnail());
posterImageUri = pictureUri.toString();
} else {
posterImageUri = "null";
}
final Movie movie = new Movie(id, title, overview, voteAverage, releaseDate, coverImageUri, posterImageUri);
AppExecutors.getInstance().diskIO().execute(new Runnable() {
@Override
public void run() {
mDb.movieDao().insertMovie(movie);
LiveData<Movie> savedMovie = mDb.movieDao().loadMovieById(movie.getId());
if (savedMovie != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(),
getString(R.string.add_favorite_movie_successful), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
private void removeFavoriteMovie() {
if (movieOnDb != null){
myMovie = movieOnDb;
}
ContentResolver contentResolver = getActivity().getContentResolver();
coverImageUri = myMovie.getCoverImageUri();
posterImageUri = myMovie.getPosterImageUri();
if (coverImageUri != null || posterImageUri != null) {
Toast.makeText(getActivity(), getString(R.string.remove_favorite_movie), Toast.LENGTH_SHORT).show();
if (coverImageUri != null) {
String coverImagePath = Uri.parse(coverImageUri).getPath();
contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.ImageColumns.DATA + "=?", new String[]{coverImagePath});
}
if (posterImageUri != null) {
String thumbnailImagePath = Uri.parse(posterImageUri).getPath();
contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.ImageColumns.DATA + "=?", new String[]{thumbnailImagePath});
}
}
AppExecutors.getInstance().diskIO().execute(new Runnable() {
@Override
public void run() {
mDb.movieDao().deleteMovie(myMovie);
final LiveData<Movie> deletedMovie = mDb.movieDao().loadMovieById(myMovie.getId());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (deletedMovie.getValue() != null) {
Toast.makeText(getActivity(),
getString(R.string.remove_favorite_movie_failed), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),
getString(R.string.remove_favorite_movie_successful), Toast.LENGTH_SHORT).show();
}
}
});
if (isSortedByFavoriteMovie){
Intent mainActivity = new Intent(getActivity(), MainActivity.class);
startActivity(mainActivity);
}
}
});
}
private void downloadFile(String imageUrl) {
try {
File f = createImageFile();
pictureUri = Uri.fromFile(f);
f.delete();
DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(imageUrl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setDestinationUri(pictureUri);
mgr.enqueue(request);
} catch (IOException e) {
e.printStackTrace();
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ IMAGES_DIR
+ getString(R.string.app_name));
Log.d(LOG_TAG, "Dir: " + storageDir);
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d(LOG_TAG, "failed to create directory");
return null;
}
}
}
} else {
Log.d(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
// Method to get the bitmap resized
public Bitmap getBitmapFromUri(Uri uri) {
if (uri == null || uri.toString().isEmpty())
return null;
Log.d("Target size", String.valueOf(targetW) + " " + String.valueOf(targetW));
InputStream input = null;
Bitmap errorImage = BitmapFactory.decodeResource(getResources(), R.drawable.noimageicon);
try {
input = getActivity().getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
Log.d("Photo size", String.valueOf(photoW) + " " + String.valueOf(photoH));
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
input = getActivity().getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
Log.e(LOG_TAG, "Failed to load image.", fne);
return errorImage;
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to load image.", e);
return errorImage;
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ioe) {
return errorImage;
}
}
}
private void loadDetailsViews() {
if (!myMovie.getTitle().equals("")) {
mBinding.titleInfo.setText(myMovie.getTitle());
} else {
mBinding.titleInfo.setText(getString(R.string.no_title));
}
if (!myMovie.getReleaseDate().equals("")) {
String releaseYear = myMovie.getReleaseDate().substring(0, 4);
String text = "<small><font color='#808080'>(" + releaseYear
+ ")" + "</font></small>";
mBinding.titleInfo.append(" ");
mBinding.titleInfo.append(Html.fromHtml(text));
mBinding.releaseDateInfo.setText(myMovie.getReleaseDate());
} else {
mBinding.releaseDateInfo.setText(getString(R.string.no_info));
}
if (myMovie.getVoteAverage() >= 0) {
mBinding.ratingInfo.setText(String.valueOf(myMovie.getVoteAverage()));
} else {
mBinding.ratingInfo.setText(getString(R.string.no_rating));
}
if (!myMovie.getOverview().equals("")) {
mBinding.synopsisInfo.setText(myMovie.getOverview());
}
movieId = myMovie.getId();
Picasso.with(getActivity())
.load(myMovie.getPosterThumbnail())
.error(R.drawable.noimageicon)
.into(mBinding.posterDetail);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
Intent intent = NavUtils.getParentActivityIntent(getActivity());
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(getActivity(), intent);
}
return super.onOptionsItemSelected(item);
}
@Override
public Loader<List<Review>> onCreateLoader(int id, Bundle bundle) {
String URL = "";
Uri baseUri = Uri.parse(BASE_QUERY_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendPath("movie");
uriBuilder.appendPath(String.valueOf(movieId));
switch (id) {
case 2:
uriBuilder.appendPath("reviews");
uriBuilder.appendQueryParameter("api_key", API_KEY);
uriBuilder.appendQueryParameter("page", "1");
URL = uriBuilder.toString();
break;
case 3:
uriBuilder.appendPath("videos");
uriBuilder.appendQueryParameter("api_key", API_KEY);
URL = uriBuilder.toString();
break;
case 4:
uriBuilder.appendPath("images");
uriBuilder.appendQueryParameter("api_key", API_KEY);
URL = uriBuilder.toString();
}
return new DetailLoader(getContext(), URL);
}
@Override
public void onLoadFinished(Loader loader, List details) {
int id = loader.getId();
switch (id) {
case 2:
mAdapter.setData(details);
if (details.isEmpty()) {
reviewLabel.setText(R.string.no_reviews);
}
reviewLabel.setVisibility(View.VISIBLE);
break;
case 3:
tAdapter.setData(details);
if (details.isEmpty()) {
trailerLabel.setText(R.string.no_trailers);
}
trailerLabel.setVisibility(View.VISIBLE);
break;
case 4:
imagesUrl = details;
displayCoverImage(imagesUrl);
break;
}
}
private void displayCoverImage(List<Movie> images) {
if (!images.isEmpty()) {
Movie firstCoverImage = images.get(0);
Picasso.with(getActivity())
.load(firstCoverImage.getCoverImageURL())
.resize(406, 228)
.error(R.drawable.noimageicon)
.into(mBinding.movieDetailImage);
} else {
mBinding.movieDetailImage.setVisibility(View.GONE);
}
}
@Override
public void onLoaderReset(@NonNull Loader<List<Review>> loader) {
int id = loader.getId();
switch (id) {
case 2:
mAdapter.clear();
break;
case 3:
tAdapter.clear();
break;
case 4:
imagesUrl.clear();
break;
}
}
@Override
public void onListTrailerClick(int clickedItemIndex) {
String trailerURL = tAdapter.getItem(clickedItemIndex).getTrailerURL();
Intent playVideo = new Intent(Intent.ACTION_VIEW, Uri.parse(trailerURL));
startActivity(playVideo);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SAVED_ID_KEY, movieId);
}
private void checkMovieInDatabase(int movieId) {
DetailMovieViewModelFactory detailMovieViewModelFactory =
new DetailMovieViewModelFactory(mDb, movieId);
final DetailMovieViewModel detailMovieViewModel =
ViewModelProviders.of(this, detailMovieViewModelFactory).get(DetailMovieViewModel.class);
detailMovieViewModel.getMovie().observe(this, new Observer<Movie>() {
@Override
public void onChanged(@Nullable Movie movie) {
detailMovieViewModel.getMovie().removeObserver(this);
if (isSortedByFavoriteMovie){
myMovie = movie;
populateUI(movie);
} else {
movieOnDb = movie;
if(movie != null){
mBinding.favoriteBtn.setChecked(true);
}
}
}
});
}
}
|
import attachUser from '../../src/middlewares/attachUser';
import UserModel from '../../src/models/user';
afterEach(() => {
jest.restoreAllMocks();
});
let email: string;
let req: any;
let res: any;
let next: any;
const setUpTest = () => {
email = 'test@gmail.com';
req = {
token: {
data: {
email,
},
},
};
res = {};
next = jest.fn();
};
afterEach(() => {
jest.clearAllMocks();
});
describe('given jwt token', () => {
beforeEach(setUpTest);
it('should attach user into request', async () => {
UserModel.findOne = jest.fn().mockResolvedValue({ email });
await attachUser(req, res, next);
expect(req.user).toEqual({ email });
});
it('should invoke next with no params', async () => {
UserModel.findOne = jest.fn().mockResolvedValue({ email });
await attachUser(req, res, next);
expect(next).toBeCalledWith();
});
});
describe('given malformed jwt token', () => {
beforeEach(setUpTest);
it('should throw err user not found', async () => {
UserModel.findOne = jest.fn().mockResolvedValue(undefined);
await attachUser(req, res, next);
expect(next).toBeCalledWith(new Error('User not found'));
});
});
describe('internal server error', () => {
beforeEach(setUpTest);
it('should throw error 500', async () => {
UserModel.findOne = jest.fn().mockRejectedValue(new Error(''));
await attachUser(req, res, next);
expect(next).toBeCalledWith(new Error('Internal server error'));
});
});
|
/*
Copyright 2012-2014 Kasper Skårhøj, SKAARHOJ, kasper@skaarhoj.com
This file is part of the Sony Deck Control RS-422 Client library for Arduino
The ClientSonyDeckControlUDP library 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.
The ClientSonyDeckControlUDP library 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 the ClientSonyDeckControlUDP library. If not, see http://www.gnu.org/licenses/.
IMPORTANT: If you want to use this library in your own projects and/or products,
please play a fair game and heed the license rules! See our web page for a Q&A so
you can keep a clear conscience: http://skaarhoj.com/about/licenses/
*/
#ifndef ClientSonyDeckControlUDP_h
#define ClientSonyDeckControlUDP_h
#include "Arduino.h"
#include "SkaarhojUDPClient.h"
// #include "SkaarhojPgmspace.h" - 23/2 2014
#define ClientSonyDeckControlUDP_BUFFERLEN 15
class ClientSonyDeckControlUDP : public SkaarhojUDPClient
{
private:
uint8_t _binarybuffer[ClientSonyDeckControlUDP_BUFFERLEN];
uint8_t _binBufferSize;
uint8_t _binarybufferCheckSum;
uint8_t _binarybufferExpectedLength;
uint8_t _lastStatusCheckSum;
// State variables:
bool _isPlaying;
bool _isRecording;
bool _isForwarding;
bool _isRewinding;
bool _isStopped;
bool _isCassetteOut;
bool _isInLocalModeOnly;
bool _isStandby;
bool _isInJogMode;
bool _isDirectionBackwards;
bool _isStill;
bool _isNearEOT;
bool _isEOT;
public:
ClientSonyDeckControlUDP();
void begin(const IPAddress ip);
void pingTimeout(uint16_t timeout);
private:
void _resetDeviceStateVariables();
void _sendStatus();
void _sendPing();
void _resetBuffer();
void _sendBuffer();
void _readFromClient();
void _parselineDispatch();
public:
bool isOnline();
bool TXready();
/********************************
* ClientSonyDeckControlUDP State methods
* Returns the most recent information we've
* got about the device state
********************************/
// Deck status:
bool isPlaying(); // If playing
bool isRecording(); // If recording
bool isForwarding(); // If fast forwarding x2 or more
bool isRewinding(); // If rewinding x1 or more
bool isStopped(); // If stopped
// Other status registers:
bool isCassetteOut();
bool isInLocalModeOnly();
bool isStandby(); // If
bool isInJogMode();
bool isDirectionBackwards();
bool isStill();
bool isNearEOT(); // 3 minutes before
bool isEOT(); // 30 seconds before
/********************************
* ClientSonyDeckControlUDP Command methods
* Asks the deck to do something
********************************/
void doPlay();
void doRecord();
void doFastForward();
void doRewind();
void doStop();
};
#endif
|
package server;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* An abstract class representing a collection which can be locked using
* a read/write lock, allowing for thread safe accesses to it
*/
public abstract class LockableCollection {
/**
* The lock used
*/
private ReadWriteLock lock;
/**
* Default constructor
*/
public LockableCollection() {
lock = new ReentrantReadWriteLock();
}
/**
* Gets the read lock of the collection
* @return the read lock of the collection
*/
public Lock readLock() {
return lock.readLock();
}
/**
* Gets the write lock of the collection
* @return the write lock of the collection
*/
public Lock writeLock() {
return lock.writeLock();
}
}
|
{#
/**
* @file
* Theme override to display primary and secondary local tasks.
*
* Available variables:
* - primary: HTML list items representing primary tasks.
* - secondary: HTML list items representing primary tasks.
*
* Each item in these variables (primary and secondary) can be individually
* themed in menu-local-task.html.twig.
*/
#}
{% set primary_attributes = primary_attributes|default(create_attribute()) %}
{% set secondary_attributes = secondary_attributes|default(create_attribute()) %}
{%
set primary_classes = primary_classes|default([
'list-reset',
'flex',
'flex-row',
'bg-marine-light',
])
%}
{%
set secondary_classes = secondary_classes|default([
'list-reset',
'flex',
'flex-row',
'bg-marine',
])
%}
{% if primary %}
<h2 class="visually-hidden">{{ 'Primary tabs'|t }}</h2>
<ul{{ primary_attributes.addClass(primary_classes) }}>{{ primary }}</ul>
{% endif %}
{% if secondary %}
<h2 class="visually-hidden">{{ 'Secondary tabs'|t }}</h2>
<ul{{ secondary_attributes.addClass(secondary_classes) }}>{{ secondary }}</ul>
{% endif %}
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faXmark } from "@fortawesome/free-solid-svg-icons";
import { Link } from "react-router-dom";
import CardBookingRecap from "./BookingWithSteps/CardBookingRecap";
const dataLabels = [
"Date",
"Time",
"Dinners",
"Occasion",
"Seating options",
"Special request",
];
const BookingSuccess = ({ data }) => {
return (
<div className="popup-container">
<Link to="/">
<div className="close">
<FontAwesomeIcon icon={faXmark} size="2x" />
</div>
</Link>
<div className="content">
<h3>Your reservation has been successfully completed.</h3>
<p>
We are waiting for you{" "}
<b>at Little Lemon, 122 Main Street, Chicago</b> on{" "}
<b>18/12/22, 8:00pm.</b>
</p>
<p className="text-strong">Next steps:</p>
<ul>
<li>
You will receive a notification remainder by SMS one hour before the
scheduled time
</li>
<li>
Our staff will call you in case you don’t show up on the time you
chose
</li>
</ul>
<div className="row gap-2 wrap">
<div className="col">
<CardBookingRecap>
<h4>Your reservation:</h4>
<ul>
{Object.entries(data).map(([k, val], i) => (
<li key={k}>
<span className="text-strong">{dataLabels[i]}:</span> {val}
</li>
))}
</ul>
</CardBookingRecap>
</div>
<div className="col">
<div id="gmaps">
<iframe
title="gmaps"
width="500"
height="280"
src="https://maps.google.com/maps?hl=en&q=58 Middle Point Rd San Francisco, California(CA), 94124+(Little Lemon)&ie=UTF8&t=&z=11&iwloc=B&output=embed"></iframe>
</div>
{/* <div className="row" style={{ justifyContent: "center" }}>
<a
href="https://www.google.com/maps?ll=37.736611,-122.379577&z=11&t=m&hl=en&gl=US&mapclient=embed&q=58+Middle+Point+Rd+San+Francisco,+CA+94124+USA"
target="blank"
className="btn-link">
<Button classes="btn-secondary btn-sm">
Open in Google Maps
</Button>
</a>
<Link to="/" className="btn-link">
<Button classes="btn-primary btn-sm">Close</Button>
</Link>
</div> */}
</div>
</div>
</div>
</div>
);
};
export default BookingSuccess;
|
import { useTranslations } from "next-intl";
import { NextIntlClientProvider, useMessages } from 'next-intl';
export default function LocaleLayout({
children,
params: {locale}
}: {
children: React.ReactNode;
params: {locale: string};
}) {
const t = useTranslations('nav');
const messages = useMessages();
return (
<html lang={locale}>
<body>
<header>
<nav>
<a href="/en">{t('english')}</a>
<a href="/de">{t('german')}</a>
</nav>
</header>
<main>
<NextIntlClientProvider
locale={locale}
messages={messages}
>
{children}
</NextIntlClientProvider>
</main>
</body>
</html>
);
}
|
Этот проект собирает текущие цены на криптовалюты с API Binance, распределяет запросы между несколькими воркерами (горрутинами) для повышения производительности и отображает обновленные цены на консоль в реальном времени. Программа также корректно обрабатывает сигналы остановки, позволяя безопасно завершить работу.
Для запуска:
```bash
go run.
```
Для остановки:
```bash
STOP
```
## Язык программирования: Go (Golang)
1. Высокопроизводительный язык с поддержкой конкурентного программирования.
+ HTTP-клиент: net/http
2. Встроенный пакет Go для выполнения HTTP-запросов к API Binance.
+ Синхронизация и конкурентное программирование: sync, context
3. Пакет sync для синхронизации горутин (wait groups, mutex).
+ Пакет context для управления жизненным циклом горутин.
4. Формат данных: JSON
+ Используется для обмена данными с API Binance. Парсинг JSON осуществляется с помощью encoding/json.
5. Конфигурационный файл: YAML
+ Конфигурационные данные хранятся в файле YAML. Для парсинга используется библиотека gopkg.in/yaml.v2.
6. Логирование: log
+ Встроенный пакет Go для логирования ошибок и другой отладочной информации.
7. Операционные сигналы: os/signal, syscall
+ Используется для обработки сигналов остановки (SIGINT, SIGTERM) и корректного завершения работы программы.
8. Ввод с клавиатуры: bufio
+ Используется для чтения команд с консоли, например, команды "STOP" для остановки программы.
## Пример структуры проекта
```go
.
├── main.go
├── worker
│ └── worker.go
├── models
│ └── models.go
├── config.yaml
└── config.example.yaml
```
## Необходимо реализовать простой парсер тикеров с биржи Бинанс.
+ Для запроса цен использовать эндпоинт
+ GET /api/v3/ticker/price https://binance-docs.github.io/apidocs/spot/en/#symbol-price-ticker.
Входные данные:
Конфиг файл в формате yaml
```yaml
symbols:
- "LTCBTC"
- "BTCUSDT"
- "EOSUSDT"
# max_workers - ограничивает количество параллельно
# запущенных воркеров, которые делают запросы на биржу
max_workers: 2
```
## Что делает программа при старте:
* Программа должна считать конфигу.
* Распределить все переданные символы равномерно по количеству групп (max_workers).
* Запустить параллельно обработку каждой группы в отдельном обработчике.
* Каждый обработчик делает запросы цен с указанного эндпоинта бинанса (в бесконечном цикле).
* Запрещается в обработчике выводить что-то в stdout, кроме ошибок.
* Все собираемые каждым обработчиком цены должны выводиться в консоль просто в порядке их получения (синхронизировать обработчики между собой не нужно).
* Дополнительно к выводу цены, в каждом лог сообщении необходимо выводить текст “changed”, если цена по конкретному символу отличается от предыдущего полученного значения по этому же символу.
* Обработчик должен быть структурой с набором из двух методов:
1. Run - собственно запуск сбора цен по набору символов (сигнатура метода может быть любой, какой пожелаете)
2. GetRequestsCount () int - сигнатура должна быть как описано тут.
+ Возвращает количество запросов сделанных на биржу, конкретным обработчиком (без учета разных символов - просто счетчик по всем сделанным запросам).
+ Ошибочные запросы тоже учитываются.
+ Программа должны выводить каждые 5 сек, сколько всего сделано запросов на биржу
+ Программа должна ожидать из stdin ключевое слово “STOP”. Когда пользователь вводит в консоль слово STOP, то обработчики должны прекратить собирать цены.Если STOP введено, программа должна дождаться когда завершится каждый обработчик и выйти.
## Ограничения и допущения
- Запрещается использовать любые библиотеки реализующие API Бинанса, такие как например https://github.com/thrasher-corp/gocryptotrader
- Запрещается внутри воркера писать что-либо в strout кроме ошибок
- Количество символов может быть любое
- Число max_workers не должно превышать количество виртуальных ядер процессора и должно принудительно устанавливаться в это значение, если превышает его
### Выходные данные:
Вот пример, что должна выводить программа:
```
EOSUSDT price:111
BTCUSDT price:222
LTCBTC price:444
EOSUSDT price:111
BTCUSDT price:222
workers requests total: 6
LTCBTC price:333 changed
EOSUSDT price:222 changed
BTCUSDT price:222
LTCBTC price:333
EOSUSDT price:111 changed
BTCUSDT price:222
LTCBTC price:333
EOSUSDT price:111
workers requests total: 15
BTCUSDT price:222
LTCBTC price:333
EOSUSDT price:111
BTCUSDT price:222
```
|
<?php
namespace App\Http\Resources\Cuti;
use App\Helpers\Datetime;
use Illuminate\Http\Resources\Json\JsonResource;
class CutiKebijakanDetailResource extends JsonResource
{
public function toArray($request)
{
return [
"id"=> $this->id,
"title"=> $this->title,
"start_month"=> Datetime::convertMonthToStringIndonesian($this->start_month),
"start_year"=> $this->start_year,
"end_month"=> Datetime::convertMonthToStringIndonesian($this->end_month),
"end_year"=> $this->end_year,
"status"=> $this->status ? 'Publish':'Belum Publish',
"document"=> $this->document,
"users" => $this->userKebijakan != null ? $this->mapUserKebijakan() : []
];
}
public function mapUserKebijakan()
{
return $this->userKebijakan->map(function ($item) {
return [
'id' => $item->id,
'full_name' => $item->user->full_name,
'total' => $item->total
];
});
}
}
|
'use client'
interface ButtonProps{
label: string; // label name of the button
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void; // function to handle the click event
center?: boolean;
}
const UpdateButton: React.FC<ButtonProps> = ({ label, onClick, center }) => {
const justifyContentClass = center ? 'flex justify-center' : 'flex justify-start'
return (
<div className={justifyContentClass}>
<button
onClick={onClick}
className="text-netural-500 rounded-2xl px-4 border-2 border-netural-500"
>
{label}
</button>
</div>
);
}
export default UpdateButton
|
# Libraries
library(tidyquant)
library(tidyverse)
library(timetk)
library(openxlsx)
# Draws stock data from three individual industries (Tech, Heath, & Retail)
# Calculates portfolio value, portfolio cost, and positioning
# time_series_analysis graphs of the stocks by industry
# snapshots and archives the data into a folder, to analyze 3 industries over the course of four months
# Draws stock data from three individual industries (Tech)
# Table 1
Tech_data_tbl <- c("AAPL","GOOG","NFLX","NVDA") %>%
tq_get(from = "2021-07-30", to = "2021-10-30")
tech_stocks = data.frame(Tech_data_tbl)
# Calculates portfolio value, portfolio cost, and positioning
tech_stocks$Units <- round(runif(1, 1, 5))
tech_stocks$Price_Bought <- (runif(1, 400, 700))
tech_stocks$Portfolio_Cost <- tech_stocks$Price_Bought * tech_stocks$Units
tech_stocks$Portfolio_Price <- tech_stocks$Units * tech_stocks$adjusted
tech_stocks$Portfolio_Revenue <- tech_stocks$Portfolio_Price - tech_stocks$Portfolio_Cost
tech_stocks
Tech_position = sum(tech_stocks$Portfolio_Revenue)
Tech_position
# tech_plot_table - for graph
tech_plot_table <- select(tech_stocks, symbol, date, adjusted, Portfolio_Revenue)
#graph
tech_plot <- tech_plot_table %>%
group_by(symbol) %>%
plot_time_series(date, adjusted,
.facet_ncol = 2,
.facet_scales = "free",
.interactive = FALSE)
tech_plot
# Archive the data into a folder to create snapshots in time of your portfolio, and stock performance
#create workbook
wb <- createWorkbook()
# add Worksheet
addWorksheet(wb, sheetName = "Stock_Anysis_Tech")
# add plot
print(tech_plot)
wb %>% insertPlot(sheet = "Stock_Anysis_Tech", startCol = "G", startRow = 3)
#add Data
writeDataTable(wb, sheet = "Stock_Anysis_Tech", x = tech_plot_table)
# save workbook
saveWorkbook(wb, "005_excel_workbook/Stock_Anysis_Tech.xlsx", overwrite = TRUE)
# Health Industry
# Table 2
Health_data_tbl <- c("TDOC","PFE","MRNA","CVS") %>%
tq_get(from = "2021-07-30", to = "2021-10-30")
health_stocks = data.frame(Health_data_tbl)
# Calculates portfolio value, portfolio cost, and positioning
health_stocks$Units <- round(runif(1, 2, 5))
health_stocks$Price_Bought <- (runif(1, 100, 130))
health_stocks$Portfolio_Cost <- health_stocks$Price_Bought * health_stocks$Units
health_stocks$Portfolio_Price <- health_stocks$Units * health_stocks$adjusted
health_stocks$Portfolio_Revenue <- health_stocks$Portfolio_Price - health_stocks$Portfolio_Cost
health_stocks
Health_position = sum(health_stocks$Portfolio_Revenue)
Health_position
# health_plot_table - for graph
health_plot_table <- select(health_stocks, symbol, date, adjusted, Portfolio_Revenue)
#graph
health_plot <- health_plot_table %>%
group_by(symbol) %>%
plot_time_series(date, adjusted,
.facet_ncol = 2,
.facet_scales = "free",
.interactive = FALSE)
health_plot
# Archive the data into a folder to create snapshots in time of your portfolio, and stock performance
#create workbook
#wb <- createWorkbook()
# add Worksheet
addWorksheet(wb, sheetName = "Stock_Anysis_Health")
# add plot
print(health_plot)
wb %>% insertPlot(sheet = "Stock_Anysis_Health", startCol = "G", startRow = 3)
#add Data
writeDataTable(wb, sheet = "Stock_Anysis_Health", x = health_plot_table)
# save workbook
saveWorkbook(wb, "005_excel_workbook/Stock_Anysis_Health.xlsx", overwrite = FALSE)
# Retail Indsutry
# Table 3
Retail_data_tbl <- c("LULU","TGT","WMT","CRI") %>%
tq_get(from = "2021-07-30", to = "2021-10-30")
retail_stocks = data.frame(Retail_data_tbl)
# Calculates portfolio value, portfolio cost, and positioning
retail_stocks$Units <- round(runif(1, 2, 10))
retail_stocks$Price_Bought <- (runif(1, 100, 195))
retail_stocks$Portfolio_Cost <- retail_stocks$Price_Bought * retail_stocks$Units
retail_stocks$Portfolio_Price <- retail_stocks$Units * retail_stocks$adjusted
retail_stocks$Portfolio_Revenue <- retail_stocks$Portfolio_Price - retail_stocks$Portfolio_Cost
retail_stocks
Retail_position = sum(retail_stocks$Portfolio_Revenue)
Retail_position
# retail_plot_table - for graph
retail_plot_table <- select(retail_stocks, symbol, date, adjusted, Portfolio_Revenue)
#graph
retail_plot <- retail_plot_table %>%
group_by(symbol) %>%
plot_time_series(date, adjusted,
.facet_ncol = 2,
.facet_scales = "free",
.interactive = FALSE)
retail_plot
# Archive the data into a folder to create snapshots in time of your portfolio, and stock performance
#create workbook
#wb <- createWorkbook()
# add Worksheet
addWorksheet(wb, sheetName = "Stock_Anysis_Retail")
# add plot
print(retail_plot)
wb %>% insertPlot(sheet = "Stock_Anysis_Retail", startCol = "G", startRow = 3)
#add Data
writeDataTable(wb, sheet = "Stock_Anysis_Retail", x = retail_plot_table)
# save workbook
saveWorkbook(wb, "005_excel_workbook/Stock_Anysis_Retail.xlsx", overwrite = FALSE)
|
import { DocSectionCode } from '@/components/doc/common/docsectioncode';
import { DocSectionText } from '@/components/doc/common/docsectiontext';
import { Calendar } from '@/components/lib/calendar/Calendar';
import { useState } from 'react';
export function ButtonBarDoc(props) {
const [date, setDate] = useState(null);
const code = {
basic: `
<Calendar value={date} onChange={(e) => setDate(e.value)} showButtonBar />
`,
javascript: `
import React, { useState } from "react";
import { Calendar } from 'primereact/calendar';
export default function ButtonBarDemo() {
const [date, setDate] = useState(null);
return (
<div className="card flex justify-content-center">
<Calendar value={date} onChange={(e) => setDate(e.value)} showButtonBar />
</div>
)
}
`,
typescript: `
import React, { useState } from "react";
import { Calendar } from 'primereact/calendar';
import { Nullable } from "primereact/ts-helpers";
export default function ButtonBarDemo() {
const [date, setDate] = useState<Nullable<Date>>(null);
return (
<div className="card flex justify-content-center">
<Calendar value={date} onChange={(e) => setDate(e.value)} showButtonBar />
</div>
)
}
`
};
return (
<>
<DocSectionText {...props}>
<p>
When <i>showButtonBar</i> is present, today and clear buttons are displayed at the footer.
</p>
</DocSectionText>
<div className="card flex justify-content-center">
<Calendar value={date} onChange={(e) => setDate(e.value)} showButtonBar />
</div>
<DocSectionCode code={code} />
</>
);
}
|
const hi = 'HELLO'
const alphaL = 'abcdefghijklmnopqrstuvwxyz'
const alphaU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
function deliverHouse1() {
setTimeout( () => {
console.log('House 1 delivered');
}, 3000)
}
function deliverHouse2(){
setTimeout( () => {
console.log('House 2 delivered');
}, 1000)
}
function deliverHouse3(){
setTimeout( () => {
console.log('House 3 delivered');
}, 2000)
}
// deliverHouse1()
// deliverHouse2()
// deliverHouse3()
// 2 -> 3 -> 1 in 3 seconds
function deliverHousescbHell() {
setTimeout( () => {
console.log('House 1 delivered');
setTimeout( () => {
console.log('House 2 delivered');
setTimeout( () => {
console.log('House 3 delivered');
}, 2000)
}, 1000)
}, 3000)
}
//deliverHousescbHell()
// 1 -> 2 -> 3 in 6 seconds
function deliverHouse1Promises() {
return new Promise( (resolve, reject) => {
setTimeout( () => {
resolve('House 1 delivered')
}, 3000)
})
}
function deliverHouse2Promises() {
return new Promise( (resolve, reject) => {
setTimeout( () => {
resolve('House 2 delivered')
}, 1000)
})
}
function deliverHouse3Promises() {
return new Promise( (resolve, reject) => {
setTimeout( () => {
resolve('House 3 delivered')
}, 2000)
})
}
// deliverHouse1Promises()
// .then(res => console.log(res))
// .then(deliverHouse2Promises)
// .then(res => console.log(res))
// .then(deliverHouse3Promises)
// .then(res => console.log(res))
// .catch(err => console.log(err))
//1 -> 2 -> 3 in 6 seconds
async function deliverHousesAsyncAwait() {
const house1 = await deliverHouse1Promises()
const house2 = await deliverHouse2Promises()
const house3 = await deliverHouse3Promises()
console.log(house1,house2, house3);
}
//deliverHousesAsyncAwait()
//1 2 3 in 6 seconds
async function getDoggo(){
try{
const res = await fetch('https://dog.ceo/api/breeds/image/random')
const data = await res.json()
console.log(data.message);
}catch(err){
console.log(err);
}
}
//getDoggo()
// https://www.codewars.com/kata/57a6633153ba33189e000074/train/javascript
// Count the number of occurrences of each character and return it as a list of tuples in order of appearance. For empty output return an empty list.
// Example:
// orderedCount("abracadabra") == [['a', 5], ['b', 2], ['r', 2], ['c', 1], ['d', 1]]
var orderedCount = function (text) {
let splitted = text.split('')
let res = []
for(let i=0 ; i<splitted.length ; i++){
if(res.find(arr => arr[0] === splitted[i])){
res[res.findIndex(arr => arr[0] === splitted[i])][1] ++
}else{
res.push([splitted[i] , 1])
}
}
return res
}
// https://www.codewars.com/kata/56d6b7e43e8186c228000637/train/javascript
// Colour plays an important role in our lifes. Most of us like this colour better then another. User experience specialists believe that certain colours have certain psychological meanings for us.
// You are given a 2D array, composed of a colour and its 'common' association in each array element. The function you will write needs to return the colour as 'key' and association as its 'value'.
// For example:
// var array = [["white", "goodness"], ...] //returns [{white: 'goodness'}, ...]
function colourAssociation(array){
return array.map(subarr => ({[subarr[0]]:subarr[1]}))
}
// console.log(colourAssociation([["red", "energy"],["yellow", "creativity"],["brown" , "friendly"],["green", "growth"]]));
// https://www.codewars.com/kata/557af4c6169ac832300000ba/train/javascript
// Our fruit guy has a bag of fruit (represented as an array of strings) where some fruits are rotten. He wants to replace all the rotten pieces of fruit with fresh ones. For example, given ["apple","rottenBanana","apple"] the replaced array should be ["apple","banana","apple"]. Your task is to implement a method that accepts an array of strings containing fruits should returns an array of strings where all the rotten fruits are replaced by good ones.
// Notes
// If the array is null/nil/None or empty you should return empty array ([]).
// The rotten fruit name will be in this camelcase (rottenFruit).
// The returned array should be in lowercase.
function removeRotten(bagOfFruits){
if(!bagOfFruits) return [] //edge case null input
else return bagOfFruits.map(fruit => fruit.replace("rotten" , "").toLowerCase())
}
// https://www.codewars.com/kata/585d7d5adb20cf33cb000235/train/javascript
// There is an array with some numbers. All numbers are equal except for one. Try to find it!
// findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
// findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55
// It’s guaranteed that array contains at least 3 numbers.
// The tests contain some very huge arrays, so think about performance.
function findUniq(arr) {
return arr.find(num => arr.indexOf(num) === arr.lastIndexOf(num))
}
// https://www.codewars.com/kata/542f3d5fd002f86efc00081a
// Write a function that generates factors for a given number.
// The function takes an integer on the standard input and returns a list of integers (ObjC: array of NSNumbers representing integers). That list contains the prime factors in numerical sequence.
// Examples
// 1 ==> []
// 3 ==> [3]
// 8 ==> [2, 2, 2]
// 9 ==> [3, 3]
// 12 ==> [2, 2, 3]
function prime_factors(n) {
if(n === 1) return []//edge case
let primeFactors = []
let temp = 2
while(temp<=n){
if(n%temp === 0){
primeFactors.push(temp)
n=n/temp
}else{
temp++
}
}
return primeFactors
}
// console.log(prime_factors(1));
// console.log(prime_factors(2));
// console.log(prime_factors(612)); // -> [2, 2, 3, 3, 17]
// https://www.codewars.com/kata/55a5c82cd8e9baa49000004c
// Complete the function that takes 3 numbers x, y and k (where x ≤ y), and returns the number of integers within the range [x..y] (both ends included) that are divisible by k.
// More scientifically: { i : x ≤ i ≤ y, i mod k = 0 }
// Example
// Given x = 6, y = 11, k = 2 the function should return 3, because there are three numbers divisible by 2 between 6 and 11: 6, 8, 10
// Note: The test cases are very large. You will need a O(log n) solution or better to pass. (A constant time solution is possible.)
function divisibleCount(x, y, k) {
//So naive way would be :
//for(x to y) check if i%k === 0
//it works just fine but we'll have issues with large cases
let res = []
for(let i=x ; i<=y ; i++){
if(i%k === 0){
res.push(i)
}
}
return res.length
}
// console.log(divisibleCount(6, 11, 2));
function divisibleCountBis(x, y, k){
//what if we turn the operation around and instead of checking if k|i we check if k*n is within [x...y] and have all of the n respecting this rule
//I.e for divisibleCount(6, 11, 2),
// check if 2*1 is in [6...11]
// check if 2*2 is in [6...11]
// check if 2*3 is in [6...11]
// check if 2*4 is in [6...11]
// check if 2*5 is in [6...11]
//first element should be Math.ceil(x/k) if Math.ceil(x/k)*k smaller than y //here it shoulbe be 3
//while last element should be Math.floor(y/k) if Math.floor(y/k)*k bigger than x //here it should be 5
//And the total possibilities should be biggest-smallest+1
let smallest, biggest
if(Math.ceil(x/k)*k <= y){
smallest = Math.ceil(x/k)
}
if(Math.floor(y/k)*k >= x){
biggest = Math.floor(y/k)
}
console.log(smallest, biggest);
if(smallest!==undefined && biggest!==undefined){
return biggest-smallest+1
}else{
return 0
}
}
// console.log(divisibleCountBis(6, 11, 2));
// console.log(divisibleCountBis(6, 8, 5));
// console.log(divisibleCountBis(0, 1, 7));
// console.log(divisibleCountBis(0, 10, 1));
function divisibleCountThrice(x, y, k) {
//This was the shortest answer, which I guess is not too far from my previous idea
return Math.floor(y/k) - Math.floor((x-1)/k)
}
// https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/javascript
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
function high(x){
//Note all words are separated by a space (no commas, dots, etc)
const alpha = 'abcdefghijklmnopqrstuvwxyz'
//Map the scores, then return the word at the index of the highest score
let words = x.split(' ')
let score = words.map(word => {
return word.split('').reduce((acc, cur) => acc + alpha.indexOf(cur) + 1, 0)
})
return words[score.indexOf(Math.max(...score))]
}
// console.log(high('man i need a taxi up to ubud')); // -> taxi
// console.log(high('what time are we climbing up the volcano')); // -> volcano
// https://www.codewars.com/kata/55c9172ee4bb15af9000005d
// We have the following sequence:
// f(0) = 0
// f(1) = 1
// f(2) = 1
// f(3) = 2
// f(4) = 4;
// f(n) = f(n-1) + f(n-2) + f(n-3) + f(n-4) + f(n-5);
// Your task is to give the number of total values for the odd terms of the sequence up to the n-th term (included). (The number n (of n-th term) will be given as a positive integer)
// The values 1 (one) is the only that is duplicated in the sequence and should be counted only once.
// E.g.
// count_odd_pentaFib(5) -----> 1 # because the terms up to 5 are: 0, 1, 1, 2, 4, 8 (only 1 is odd and counted once)
// Other examples:
// count_odd_pentaFib(10) ------> 3 #because the odds terms are: [1, 1, 31, 61] (three different values)
// count_odd_pentaFib(15) ------> 5 # beacause the odd terms are: [1, 1, 31, 61, 1793, 3525] (five different values)
// Good luck !!
// (Your code should be fast. Many moderate high values will be waiting to test it.)
function countOddPentaFib(n) {
let count = 1
for (let i = 3; i <= n; i++)
if (i % 6 == 1 || i % 6 == 2) count++
return count
}
// https://www.codewars.com/kata/56b3b9c7a6df24cf8c00000e/train/javascript
// A nested list (or array in JavaScript) is a list that apears as a value inside another list,
// [item, item, [item, item], item]
// in the above list, [item, item] is a nested list.
// Your goal is to write a function that determines the depth of the deepest nested list within a given list.
// return 1 if there are no nested lists. The list passed to your function can contain any data types.
// A few examples:
// arrayDepth([true]) // returns 1
// arrayDepth([]) // returns 1
// arrayDepth([2, "yes", [true, false]]) // returns 2
// arrayDepth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]) // returns 6
// arrayDepth([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]) // returns 2
function arrayDepth(array) {
//We are going to check if array contains an array
//And flat() it until it doesn't
let counter = 1
let arr = array.slice()
while(arr.some(el => Array.isArray(el))){
arr = arr.flat()
counter++
}
return counter
}
// console.log(arrayDepth([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]));
// console.log(arrayDepth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]));
//I believe it is working, codewars doesn't support .flat() method, so here is an other solution:
function arrayDepthBis(array) {
let counter = 1
let arr = array.slice()
while(arr.some(el => Array.isArray(el))){
//arr.flat() is equivalent to arr.reduce((acc, val) => acc.concat(val), [])
arr = arr.reduce((acc, cur) => acc.concat(cur) , [])
counter++
}
return counter
}
// console.log(arrayDepthBis([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]));
// console.log(arrayDepthBis([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]));
// https://www.codewars.com/kata/5629b94e34e04f8fb200008e/train/javascript
// Every positive integer number, that is not prime, may be decomposed in prime factors. For example the prime factors of 20, are:
// 2, 2, and 5, because: 20 = 2 . 2 . 5
// The first prime factor (the smallest one) of 20 is 2 and the last one (the largest one) is 5. The sum of the first and the last prime factors, sflpf of 20 is: sflpf = 2 + 5 = 7
// The number 998 is the only integer in the range [4, 1000] that has a value of 501 , so its sflpf equals to 501, but in the range [4, 5000] we will have more integers with sflpf = 501 and are: 998, 1996, 2994, 3992, 4990.
// We need a function sflpf_data() (javascript: sflpfData()that receives two arguments, val as the value of sflpf and nMax as a limit, and the function will output a sorted list of the numbers between 4 to nMax(included) that have the same value of sflpf equals to val.
// Let's see some cases:
// sflpf_data(10, 100) == [21, 25, 63]
// /// the prime factorization of these numbers are:
// Number Prime Factorization Sum First and Last Prime Factor
// 21 = 3 . 7 ----> 3 + 7 = 10
// 25 = 5 . 5 ----> 5 + 5 = 10
// 63 = 3 . 3 . 7 ----> 3 + 7 = 10
// sflpf_data(10, 200) == [21, 25, 63, 105, 125, 147, 189]
// sflpf_data(15, 150) == [26, 52, 78, 104, 130]
// (Advice:Try to discard primes in a fast way to have a more agile code)
function sflpfData(k, nMax){
//naive way :
//I gather a list of all prime factors for each number in [4...nMax]
//I keep those with max+min === k
let res = []
for(let i=4 ; i<=nMax ; i++){
let pFactors = primeFactors(i)
let minPFactor = pFactors.shift()
let maxPFactor = pFactors.pop()
if(minPFactor+maxPFactor === k){
res.push(i)
}
}
return res
function primeFactors(n) {
//returns the list of primes factors
// from : https://www.codewars.com/kata/542f3d5fd002f86efc00081a
if(n === 1) return []//edge case
let primeFactors = []
let temp = 2
while(temp<=n){
if(n%temp === 0){
primeFactors.push(temp)
n=n/temp
}else{
temp++
}
}
return primeFactors
}
// console.log(primeFactors(1)); // -> []
// console.log(primeFactors(2)); // -> [2]
// console.log(primeFactors(612)); // -> [2, 2, 3, 3, 17]
}
// console.log(sflpfData(10, 200)); // -> [21, 25, 63, 105, 125, 147, 189]
// console.log(sflpfData(15, 150)); // -> [26, 52, 78, 104, 130]
// console.log(sflpfData(501, 5000)); // -> [998, 1996, 2994, 3992, 4990]
//It works, I was afraid it was rather long in terms of memory and time but in turned out fine. Solutions all use this approach.
|
@extends('layouts.master')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-4">
<h4 class="form-header">{{ __('Sign In') }}</h4>
<section class="form-container">
<form method="POST" action="{{ route('login') }}">
@csrf
<div class="form-group row">
<label for="email" class="email-label">{{ __('E-Mail Address') }}</label>
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror"
name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="form-group row form-group-bottom">
<div class="position-wrapper">
<label for="password" class="password-label">{{ __('Password') }}</label>
<input id="password" type="password"
class="form-control @error('password') is-invalid @enderror" name="password"
required autocomplete="current-password">
<a class="position-button"
href="{{ route('password.request') }}">{{ __('Forgot?') }}</a>
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<input class="form-check-input" type="checkbox" name="remember"
id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
<div class="form-group row mb-0">
<button type="submit" class="btn btn-primary btn-block">
{{ __('Login') }}
</button>
</div>
</form>
</section>
</div>
</div>
</div>
@endsection
|
import { useContext, useState, useEffect } from "react";
import { ImSpinner10 } from "react-icons/im";
import PropTypes from "prop-types";
import { useNavigate } from "react-router-dom";
import { Form, Input } from "antd";
import AuthContext from "../contexts/auth_context";
import usePrivateAxios from "../../configs/networks/usePrivateAxios";
function AddGroupPresentationModalBody({ addingType, setShowModal }) {
const [isLoading, setIsLoading] = useState(false);
const { user } = useContext(AuthContext);
const [errorMess, setErrorMess] = useState(null);
const [service, setService] = useState("");
const navigate = useNavigate();
const privateAxios = usePrivateAxios();
useEffect(() => {
if (addingType === 1) {
setService("group");
} else {
setService("presentation");
}
}, [addingType]);
const onFinish = async (data) => {
setIsLoading(true);
console.log(data);
const url = addingType === 1 ? `group/create` : `presentation/create`;
const params =
addingType === 1
? { username: user.username, groupname: data.name }
: { presentationName: data.name };
console.log(url);
console.log(params);
privateAxios
.get(url, { params })
.then((response) => {
console.log(response);
setIsLoading(false);
setShowModal(0);
if (addingType === 1) {
navigate(`/group_detail/${response?.data?.lastID ?? 0}`);
} else {
navigate(`/presentation/${response?.data?.presentationId ?? 0}/edit`);
}
})
.catch((error) => {
console.log(error);
setErrorMess(error.response.data.error);
setIsLoading(false);
});
};
const onFinishFailed = (error) => {
console.log(error);
setErrorMess(error.errorFields[0].errors);
};
return (
<div className="rounded-md w-full flex flex-col">
<Form
layout="vertical"
requiredMark="optional"
validateTrigger="onSubmit"
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
className="text-sm font-medium text-gray-700 mb-1"
label={`${addingType === 1 ? "Group" : "Presentation"} name`}
name="name"
rules={[
{
required: true,
message: "Name is required.",
whitespace: true
}
]}
help=""
validateStatus=""
>
<Input
id="name"
className="shadow-sm
focus:ring-purple-600 focus:border-purple-500
focus:shadow-purple-300 focus:shadow-md
hover:border-purple-400
block w-full sm:text-sm border-gray-300
px-2 py-2 bg-white border rounded-md "
placeholder="ABC"
/>
</Form.Item>
<p className="text-red-400 text-sm">{errorMess}</p>
<Form.Item>
<button
type="submit"
data-mdb-ripple="true"
data-mdb-ripple-color="light"
className="inline-flex mt-1 float-right justify-center py-2 px-4 border border-transparent
shadow-sm text-sm font-medium rounded-md text-white bg-purple-700
hover:bg-purple-600 focus:outline-none focus:bg-purple-600"
>
{isLoading ? (
<div className="flex justify-center items-center">
<ImSpinner10 className="animate-spin h-5 w-5 mr-3" />
Adding {service}...
</div>
) : (
`Add ${service}`
)}
</button>
</Form.Item>
</Form>
</div>
);
}
AddGroupPresentationModalBody.propTypes = {
addingType: PropTypes.number,
setShowModal: PropTypes.func
};
AddGroupPresentationModalBody.defaultProps = {
addingType: 0,
setShowModal: null
};
export default AddGroupPresentationModalBody;
|
import React, { useContext, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import Loader from "../../Common/Loader/Loader";
import { useForm } from "react-hook-form";
import "./ProfessorVocabulary.css";
import { UserContext } from "../../../Context/UserContext";
import AddVocabulary from "./AddVocabulary";
function ProfessorVocabulary() {
const [curent_topic, setCurrentTopic] = useState("");
const { id } = useParams();
const { user } = useContext(UserContext);
const navigate = useNavigate();
const [words, setWords] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [modal, setModal] = useState(false);
const [showButton, setShowButton] = useState(false);
const [curent_word, setCurrentWord] = useState({});
const [isUpdate, setIsUpdate] = useState(false);
const toggleModal = () => {
setModal(!modal);
};
const AddToggle = () => {
setIsUpdate(false);
toggleModal();
};
const updateToggle = (word) => {
setIsUpdate(true);
setCurrentWord(word);
toggleModal();
};
if (modal) {
document.body.classList.add("active-modal");
} else {
document.body.classList.remove("active-modal");
}
const {
register: vocabulary_topic,
handleSubmit,
formState: { errors },
} = useForm();
const goBack = () => {
navigate("/professor/vocabulary");
};
async function fetchVocabulary() {
try {
setIsLoading(true);
const response = await fetch(
`${process.env.REACT_APP_API_BASE_URL}/Vocabulary/GetVocabularyByTopic/${id}`
);
setIsLoading(false);
if (!response.ok) {
const errorData = await response.json();
toast.error(`${errorData.message}`, {
position: toast.POSITION.BOTTOM_RIGHT, // Vị trí hiển thị
autoClose: 5000, // Tự động đóng sau 3 giây
closeOnClick: true, // Đóng khi click
pauseOnHover: true, // Tạm dừng khi di chuột qua
draggable: true, // Có thể kéo thông báo
});
}
const data = await response.json();
setWords(data);
} catch (error) {
toast.error(`${error}`, {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 5000,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
}
}
async function fetchVocabularyTopic() {
setIsLoading(true);
try {
const response = await fetch(
`${process.env.REACT_APP_API_BASE_URL}/VocTopic/GetVocTopicById/${id}`
);
if (!response.ok) {
const errorData = await response.json();
toast.error(`${errorData.message}`, {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 5000,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
}
const data = await response.json();
setCurrentTopic(data);
setIsLoading(false);
} catch (error) {
toast.error(`${error}`, {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 5000,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
}
}
useEffect(() => {
fetchVocabulary();
fetchVocabularyTopic();
window.scrollTo(0, 0);
}, []);
useEffect(() => {
if (!modal) {
fetchVocabulary();
}
window.scrollTo(0, 0);
}, [modal]);
const handleUpdateVocabularyTopic = async (register) => {
setIsLoading(true);
try {
const response = await fetch(
`${process.env.REACT_APP_API_BASE_URL}/VocTopic/UpdateVocTopic/${id}&&${user.idUser}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${user.token}`,
},
body: JSON.stringify({
name: register.name,
}),
}
);
setIsLoading(false);
if (!response.ok) {
toast.error("Chỉnh sửa chủ đề từ vựng thất bại", {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 5000,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
} else {
toast.success("Chỉnh sửa chủ đề từ vựng thành công", {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 10000,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
}
} catch (error) {
toast.error(`${error}`, {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
}
};
const handleDeleteVocabulary = async (id) => {
setIsLoading(true);
try {
const response = await fetch(
`${process.env.REACT_APP_API_BASE_URL}/Vocabulary/DeleteVocabulary/${id}`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${user.token}`,
},
body: JSON.stringify({}),
}
);
setIsLoading(false);
if (!response.ok) {
toast.error(`Xóa từ vựng thất bại`, {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 5000,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
} else {
toast.success("Xóa từ vựng thành công", {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 10000,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
fetchVocabulary();
}
} catch (error) {
toast.error(`${error}`, {
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
});
}
};
if (isLoading) {
return <Loader />;
}
return (
<>
<AddVocabulary
toggleModal={toggleModal}
modal_on={modal}
idTopic={id}
isUpdate={isUpdate}
current_word={curent_word}
/>
<div className="professor-vocabulary">
<div className="professor-managment-sub-title">
<h3>QUẢN LÝ CHỦ ĐỀ TỪ VỰNG</h3>
</div>
<form
className="update-voc-topic"
onSubmit={handleSubmit(handleUpdateVocabularyTopic)}
>
<div style={{ width: "100%", textAlign: "center" }}>
<div className="input-field">
<input
type="text"
defaultValue={curent_topic.name}
onFocus={() => setShowButton(true)}
{...vocabulary_topic("name", { required: true })}
/>
</div>
<error>
{errors.name?.type === "required" && "Không được để trống tên"}
</error>
</div>
{showButton && (
<input
type="submit"
className="vocabulary-submit"
value="Cập nhật"
></input>
)}
</form>
<div className="professor-add-button-wrapper">
<img
onClick={goBack}
width="50"
height="50"
src="https://img.icons8.com/ios-filled/50/2d9358/reply-arrow.png"
alt="reply-arrow"
/>
<div className="professor-add-button" onClick={AddToggle}>
<img
width="34"
height="34"
src="https://img.icons8.com/doodle/48/add.png"
alt="add"
/>
<h3>THÊM TỪ MỚI</h3>
</div>
</div>
<div className="wordList-wrapper">
{words &&
words.map((word, index) => {
return (
<div key={index} className="wordList-item">
<div className="eng-word">{word.engWord}</div>
<div className="word-type">{word.wordType}</div>
<div className="word-meaning">{word.meaning}</div>
<div className="btn-wrapper">
<button
className="delete-btn"
onClick={() => handleDeleteVocabulary(word.idVoc)}
>
Xóa
</button>
<button
className="update-btn"
onClick={() => updateToggle(word)}
>
Sửa
</button>
</div>
</div>
);
})}
</div>
</div>
</>
);
}
export default ProfessorVocabulary;
|
const BaseModel = require('../../base-model');
const { createLoaders } = require('./loaders');
const { countryCreateError, statusTypes, reverseAddressError } = require('../root/enums');
const { find } = require('lodash');
const {
addLocalizationField,
transformToCamelCase,
formatError,
} = require('../../lib/util');
const {
redisTimeParameter,
googleMapsReverseGeocodeApiKey,
} = require('../../../config');
const Axios = require('axios');
class Country extends BaseModel {
constructor(db, context) {
super(db, 'countries', context);
this.loaders = createLoaders(this);
}
filterCountries(query, filters) {
if (typeof filters.status === 'undefined') {
filters.status = 'ALL';
}
if (filters.status !== 'ALL') {
query.where('countries.status', filters.status);
}
if (filters.searchText) {
filters.searchText = filters.searchText.toLowerCase().trim();
query.whereRaw(
'(LOWER(countries.name) like ? or countries.name_ar like ? or countries.name_tr like ? or LOWER(countries.iso_code) LIKE ? )'
, [`%${filters.searchText}%`, `%${filters.searchText}%`, `%${filters.searchText}%`, `%${filters.searchText}%`],
);
}
return query;
}
async getTimezoneIdentifier(countryId) {
const query = this.roDb(this.tableName)
.select('time_zone_identifier')
.where('id', countryId);
const [object] = await this.context.sqlCache(
query,
redisTimeParameter.oneDayInSeconds
);
if (object) {
return object.timeZoneIdentifier;
}
return null;
}
async getByCode(code, filters = {}) {
code = (code || '').toUpperCase();
let query = this.roDb(this.tableName).where('iso_code', code);
query = this.filterCountries(query, filters);
const country = addLocalizationField(
await this.context.sqlCache(query, redisTimeParameter.oneHourInSeconds),
'name'
);
return country ? country[0] : null;
}
async getById(id) {
const query = this.roDb(this.tableName).where('id', id);
const country = addLocalizationField(
await this.context.sqlCache(query, redisTimeParameter.oneHourInSeconds),
'name'
);
return country ? country[0] : null;
}
async getAll(filters) {
let query = super.getAll();
query = this.filterCountries(query, filters);
return addLocalizationField(
await this.context.sqlCache(query, redisTimeParameter.oneHourInSeconds),
'name'
);
}
async getAllActive() {
return addLocalizationField(
await super.getAll().where('status', statusTypes.ACTIVE),
'name'
);
}
async getByCurrencyId(currencyId) {
return addLocalizationField(
await super
.getAll()
.where('currency_id', currencyId)
.first(),
'name'
);
}
async getByIsoCode(iso) {
iso = (iso || '').toUpperCase();
return addLocalizationField(
await super
.getAll()
.where('iso_code', iso)
.first(),
'name'
);
}
async getActiveByIsoCode(iso) {
iso = (iso || '').toUpperCase();
return this.roDb(this.tableName)
.where('iso_code', iso)
.andWhere('status', 'ACTIVE')
.first();
}
async getByCityId(cityId) {
const city = await this.context.city.getById(cityId);
return this.getById(city.countryId);
}
async validate(countryInput) {
const errors = [];
const currency = await this.context.currency.getById(
countryInput.currencyId
);
if (!currency) {
errors.push(countryCreateError.INVALID_CURRENCY);
}
const countries = await this.roDb(this.tableName).whereRaw(
`(countries.name ILIKE '${countryInput.name}' or countries.iso_code ILIKE '${countryInput.isoCode}' )`
);
if (countries.length > 1) {
errors.push(countryCreateError.ALREADY_EXISTS);
} else if (countries.length === 1 && (!countryInput.id || countries[0].id !== countryInput.id)) {
errors.push(countryCreateError.ALREADY_EXISTS);
}
return errors;
}
async getCountryCurrencyLookup() {
const query = `select
c.id as country_id ,
c.iso_code as country_iso_code,
c."name" as country_name,
c."name_ar" as country_name_ar,
c."name_tr" as country_name_tr,
c.dial_code as country_dial_code,
c.locations_radius as country_locations_radius,
c.delivery_fee as country_delivery_fee,
c.service_fee as country_service_fee,
c.service_phone_number as country_service_phone_number,
c.vat as country_vat,
c.vat_id as country_vat_id,
c.is_referral_active,
c.sender_referral_amount,
c.receiver_referral_amount,
c.minimum_delivery_order_amount,
c.flag_photo,
cur.id as currency_id,
cur."name" as currency_name,
cur.iso_code as currency_iso_code,
cur.symbol as currency_symbol,
cur.symbol_ar as currency_symbol_ar,
cur.symbol_tr as currency_symbol_tr,
cur.subunit_name as currency_subunit_name,
cur.subunit_name_ar as currency_subunit_name_ar,
cur.subunit_name_tr as currency_subunit_name_tr,
cur.decimal_place as currency_decimal_place,
cur.lowest_denomination as currency_lowest_denomination
from countries c
join currencies cur on c.currency_id = cur.id
where c.status ='ACTIVE' and cur.status = 'ACTIVE'`;
// Talk about bad localization design :/
return addLocalizationField(
addLocalizationField(
addLocalizationField(
await this.roDb
.raw(query)
.then(result => transformToCamelCase(result.rows)),
'countryName'
),
'currencySymbol'
),
'currencySubunitName'
);
}
async validateGeocoding(geocodingInput) {
/**
* For this validation there are 2 ways
* First one is Geocoding MS, second one is new db field(MultiPolygon)
* Geocoding MicroService is not running that why we can not use
* Second way is already update db and call with location.
* That's why we ignored validation part
*/
const errors = [];
/*
const query = this.roDb(this.tableName)
.where('status', statusTypes.ACTIVE)
.WhereRaw(`ST_Intersects(geom, ST_SetSRID(ST_Point(${geocodingInput.longitude},${geocodingInput.latitude}), 4326))`);
const country = await query;
if (isEmpty(country)) {
errors.push(reverseAddressError.OUT_OF_SERVICE_COUNTRY);
}
*/
return errors;
}
async getAddressFromGeocoding(geocodingInput, preferredLanguage) {
try {
const response = await Axios.get(
'https://maps.googleapis.com/maps/api/geocode/json',
{params: { latlng: geocodingInput.latitude + ',' + geocodingInput.longitude, key: googleMapsReverseGeocodeApiKey, language: preferredLanguage }}
);
const addresses = response.data.results;
const formattedAddress = addresses[0].formatted_address;
const establishmentAddress = (find(addresses, address => address.types.includes('establishment')))?.address_components || null;
const streetAddress = (find(addresses, address => address.types.includes('street_address')))?.address_components || null;
const premiseAddress = (find(addresses, address => address.types.includes('premise')))?.address_components || null;
const localtyAddress = (find(addresses, address => address.types.includes('locality')))?.address_components || null;
const administrativeAddress = (find(addresses, address => address.types.includes('administrative_area_level_1')))?.address_components || null;
const countryAddress = (find(addresses, address => address.types.includes('country')))?.address_components || null;
const countryCode = (find(countryAddress, element => element.types.includes('country')))?.short_name || null;
const country = countryCode ? addLocalizationField(await this.getByCode(countryCode), 'name') : null;
if (!country || country.status !== 'ACTIVE') return formatError([reverseAddressError.OUT_OF_SERVICE_COUNTRY]);
let countryName = country.name.en;
switch (preferredLanguage) {
case 'ar':
countryName = country.name.ar;
break;
case 'tr':
countryName = country.name.tr;
break;
default:
break;
}
//const description = '(' + geocodingInput.latitude + ',' + geocodingInput.longitude + ')';
const addressList = [establishmentAddress, streetAddress, premiseAddress].filter(n => n);
const areaLevel = (find(administrativeAddress, element => element.types.includes('administrative_area_level_1')))?.long_name || null;
const locality = (find(localtyAddress, element => element.types.includes('locality')))?.long_name || null;
if (addressList.length > 0) {
const searchList = ['subpremise', 'premise', 'street_number', 'route', 'neighborhood', 'sublocality', 'locality', 'postal_code'];
const addressObject = {};
searchList.forEach(search => {
addressList.forEach(address => {
const value = (find(address, element => element.types.includes(search)))?.long_name || null;
if (value && !addressObject[search]) {
addressObject[search] = value;
}
});
});
/*
const address = establishmentAddress || streetAddress || premiseAddress;
const subpremise = (find(address, element => element.types.includes('subpremise')))?.long_name || null;
const premise = (find(address, element => element.types.includes('premise')))?.long_name || null;
const streetNumber = (find(address, element => element.types.includes('street_number')))?.long_name || null;
const route = (find(address, element => element.types.includes('route')))?.long_name || null;
const neighborhood = (find(address, element => element.types.includes('neighborhood')))?.long_name || null;
const sublocality = (find(address, element => element.types.includes('sublocality')))?.long_name || null;
const city = (find(address, element => element.types.includes('locality')))?.long_name || null;
const postalCode = (find(address, element => element.types.includes('postal_code')))?.long_name || null;
*/
const titleArrays = [addressObject.subpremise, addressObject.premise, addressObject.neighborhood, addressObject.route, addressObject.city].filter(n => n);
//const elementArrays = [addressObject.subpremise, addressObject.premise, addressObject.streetNumber, addressObject.route, addressObject.neighborhood, addressObject.sublocality, addressObject.city, addressObject.postalCode].filter(n => n);
const title = titleArrays[0] || ((locality || areaLevel) ? (locality || areaLevel) + ' ' + countryName : countryName);
//description = elementArrays.length > 0 ? elementArrays.join(',') : description;
const reverseAddress = {
title,
description: formattedAddress,
subpremise: addressObject.subpremise,
premise: addressObject.premise,
streetNumber: addressObject.street_number,
route: addressObject.route,
neighborhood: addressObject.neighborhood,
sublocality: addressObject.sublocality,
city: addressObject.locality,
postalCode: addressObject.postal_code,
countryCode,
countryId: country.id,
};
return {address: reverseAddress};
}
return { address:
{
title: (locality || areaLevel) ? (locality || areaLevel) + ' ' + countryName : countryName,
description: formattedAddress,
countryCode,
countryId: country.id
}
};
} catch (error) {
return formatError([reverseAddressError.INVALID_GEOCODING]);
}
/*
const options = {
provider: 'google',
apiKey: googleMapsReverseGeocodeApiKey,
language: preferredLanguage.toLowerCase()
};
const geoCoder = nodeGeocoder(options);
//console.log(await geoCoder.reverse({ lat: geocodingInput.latitude, lon: geocodingInput.longitude }));
try {
const {city, state, zipcode, streetName, streetNumber, countryCode, extra} = first(await geoCoder.reverse({ lat: geocodingInput.latitude, lon: geocodingInput.longitude }));
const neighborhood = extra.neighborhood;
//console.log(extra)
//const establishment = extra.establishment
const country = await this.getByCode(countryCode);
if (!country || country.status !== 'ACTIVE') return formatError([reverseAddressError.OUT_OF_SERVICE_COUNTRY]);
//console.log( line1, city, state, zipcode, streetName, streetNumber, countryCode, neighbourhood)
//console.log(country)
let elementArrays = [streetName, streetNumber, neighborhood, city, state, zipcode];
elementArrays = elementArrays.filter(n => n);
if (elementArrays.length === 0) return formatError([reverseAddressError.INVALID_ADDRESS]);
const formattedAddress = elementArrays.join(',');
const reverseAddress = {
city,
state,
postalCode: zipcode,
route: streetName,
streetNumber,
neighborhood,
formattedAddress,
countryCode,
countryId: country.id
};
return {address: reverseAddress};
} catch (error) {
return formatError([reverseAddressError.INVALID_GEOCODING]);
}
*/
}
}
module.exports = Country;
|
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function numberToWords($number)
{
$ones = array(
1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five',
6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten',
11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen',
15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
19 => 'nineteen'
);
$tens = array(
2 => 'twenty', 3 => 'thirty', 4 => 'forty', 5 => 'fifty',
6 => 'sixty', 7 => 'seventy', 8 => 'eighty', 9 => 'ninety'
);
$words = array();
if ($number < 0) {
$words[] = 'minus';
$number = abs($number);
}
if ($number < 20) {
$words[] = $ones[$number];
} elseif ($number < 100) {
$words[] = $tens[($number / 10)];
if ($number % 10) {
$words[] = $ones[$number % 10];
}
} elseif ($number < 1000) {
$words[] = $ones[($number / 100)] . ' hundred';
if ($number % 100) {
$words[] = $this->numberToWords($number % 100);
}
} else {
$baseUnit = array('', 'thousand', 'million', 'billion', 'trillion', 'quadrillion');
$base = pow(1000, floor(log($number, 1000)));
$unit = $number / $base;
$words[] = $this->numberToWords($unit) . ' ' . $baseUnit[floor(log($number, 1000))];
if ($number % $base) {
$words[] = $this->numberToWords($number % $base);
}
}
return implode(' ', $words);
}
}
|
<template>
<div class="request-result">
<div>
<el-row :gutter="8" type="flex" align="middle" class="info">
<el-col :span="2">
<div class="method">
{{request.method}}
</div>
</el-col>
<el-col :span="8">
<el-tooltip effect="dark" :content="request.url" placement="bottom" :open-delay="800">
<div class="url">{{request.url}}</div>
</el-tooltip>
</el-col>
<el-col :span="8">
<div class="url"> {{$t('api_report.start_time')}}:{{request.startTime | timestampFormatDate(true) }}
</div>
</el-col>
</el-row>
</div>
<el-collapse-transition>
<div v-show="isActive">
<ms-response-text :request-type="requestType" v-if="isCodeEditAlive" :response="request.responseResult" :request="request"/>
</div>
</el-collapse-transition>
</div>
</template>
<script>
import MsResponseText from "./ResponseText";
export default {
name: "MsRequestSubResultTail",
components: {MsResponseText},
props: {
request: Object,
scenarioName: String,
requestType: String
},
data() {
return {
isActive: true,
activeName: "sub",
isCodeEditAlive: true
}
},
methods: {
active() {
this.isActive = !this.isActive;
},
reload() {
this.isCodeEditAlive = false;
this.$nextTick(() => (this.isCodeEditAlive = true));
}
},
watch: {
'request.responseResult'() {
this.reload();
}
},
computed: {
assertion() {
return this.request.passAssertions + " / " + this.request.totalAssertions;
},
hasSub() {
return this.request.subRequestResults.length > 0;
},
}
}
</script>
<style scoped>
.request-result {
width: 100%;
min-height: 40px;
padding: 2px 0;
}
.request-result .info {
background-color: #F9F9F9;
margin-left: 20px;
cursor: pointer;
}
.request-result .method {
color: #1E90FF;
font-size: 14px;
font-weight: 500;
line-height: 40px;
padding-left: 5px;
}
.request-result .url {
color: #7f7f7f;
font-size: 12px;
font-weight: 400;
margin-top: 4px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
word-break: break-all;
}
.request-result .tab .el-tabs__header {
margin: 0;
}
.request-result .text {
height: 300px;
overflow-y: auto;
}
.sub-result .info {
background-color: #FFF;
}
.sub-result .method {
border-left: 5px solid #1E90FF;
padding-left: 20px;
}
.sub-result:last-child {
border-bottom: 1px solid #EBEEF5;
}
.request-result .icon.is-active {
transform: rotate(90deg);
}
</style>
|
package telegram_ai_bot
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/go-telegram-bot-api/telegram-bot-api/v5"
"io"
"net/http"
"strings"
)
const gptOpenAiUrl = "https://api.openai.com/v1/chat/completions"
func explainImage(message *tgbotapi.Message, gptModel string) {
imageBytes := DownloadLatestPhoto(message)
imageString := base64.StdEncoding.EncodeToString(imageBytes)
imageBody := buildImageBody(message.Caption, imageString, gptModel)
base64FormatImageBody := strings.Replace(imageBody,
"\"image_url\":{\"url\":\"",
"\"image_url\":{\"url\":\"data:image/jpeg;base64,",
1)
payload := strings.NewReader(base64FormatImageBody)
chatProperties, keyExists := telegramConfig.Chats[message.Chat.ID]
if !keyExists {
fmt.Println("Key does not exists!")
return
}
request, err := http.NewRequest("POST", gptOpenAiUrl, payload)
if err != nil {
fmt.Println("Error:", err)
return
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", "Bearer "+chatProperties.Llm.OpenAiGpt.ApiKey)
response, err := (&http.Client{}).Do(request)
if err != nil {
fmt.Println("Error:", err)
return
}
//fmt.Printf("response status: %s\n", response.Status)
defer response.Body.Close()
// Read the response body
body, err := io.ReadAll(response.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
//fmt.Printf("response body: %s", body)
var deserializedBody BodyResponse
err = json.Unmarshal(body, &deserializedBody)
if err != nil {
fmt.Println("Error:", err)
return
}
responseMessage := deserializedBody.Choices[len(deserializedBody.Choices)-1].Message.Content
telegramMessage := tgbotapi.NewMessage(message.Chat.ID, responseMessage)
telegramMessage.ParseMode = tgbotapi.ModeMarkdown
_, err = bot.Send(telegramMessage)
if err != nil {
fmt.Println("Error:", err)
return
}
}
func buildImageBody(caption string, image string, gptModel string) string {
base64Url := image
// f"data:image/jpeg;base64,{base64_image}"
bodyRequest := BodyRequestImage{
Model: gptModel,
Messages: []BodyRequestImageMessage{{
Role: "user",
Content: []BodyRequestImageMessageContent{
BodyRequestImageMessageContentText{
Type: "text",
Text: caption,
},
BodyRequestImageMessageContentImage{
Type: "image_url",
ImageUrl: BodyRequestImageMessageContentImageUrl{
Url: base64Url,
},
},
},
}},
MaxTokens: 300,
}
jsonBytes, err := json.Marshal(bodyRequest)
if err != nil {
fmt.Println("Error:", err)
return ""
}
return string(jsonBytes)
}
type BodyRequestImageMessageContentImageUrl struct {
Url string `json:"url"`
}
type BodyRequestImageMessageContentText struct {
Type string `json:"type"`
Text string `json:"text"`
//ImageUrl BodyRequestImageMessageContentImageUrl `json:"image_url"`
}
type BodyRequestImageMessageContentImage struct {
Type string `json:"type"`
//Text string `json:"text"`
ImageUrl BodyRequestImageMessageContentImageUrl `json:"image_url"`
}
type BodyRequestImageMessageContent interface {
}
type BodyRequestImageMessage struct {
Role string `json:"role"`
Content []BodyRequestImageMessageContent `json:"content"`
}
type BodyRequestImage struct {
Model string `json:"model"`
Messages []BodyRequestImageMessage `json:"messages"`
MaxTokens int `json:"max_tokens"`
}
|

## About
`Termux-box MOD` es simplemente [Termux-box](https://github.com/olegos2/termux-box) pero con varias modificaciones sobre rendimiento y compatibilidades. Tiene las mísmas características: (rootfs preconfigurado con [Box86](https://github.com/ptitSeb/box86), [Box64](https://github.com/ptitSeb/box64), [Wine](https://www.winehq.org/) y [DXVK](https://github.com/doitsujin/dxvk) instalados.)
Está enfocado en el funcionamiento de `Resident Evil 7: Biohazard`, pero en el camino han funcionado otros juegos que no funcionaban, tal como `Gang Beasts`.
## Installation
Despues de instalado, el comando de inicio es `termux-box`
Requisitos:
[Termux](https://f-droid.org/repo/com.termux_118.apk),
[Termux-X11](https://raw.githubusercontent.com/olegos2/termux-box/main/components/termux-x11-arm64-v8a-debug-latest.apk) para poder usar Turnip dri3.
Abrir Termux y pegar el siguiente comando:
```
curl -s -o x https://raw.githubusercontent.com/GabiAle97/termux-box/main/install && chmod +x x && ./x
```
Cerca del final de la instalación, será necesario completar una selección geográfica simple. La instalación es lenta, se puede salir de Termux mientras se ejecuta la instalación y luego de un tiempo volver a completar dicha selección, y habrá terminado.
## Configuration
La configuración usada en `Termux-X11` para que se vea todo correctamente en 1280x720 fue:
* `Display resolution mode`: exact
* `Display resolution`: 1280x720
* `Stretch to fit display`: ✅
* `Reseed Screen While Soft Keyboard is open`: ❌
* `PIP Mode`: ❌
* `Fullscreen on device display`: ✅
* `Force Landscape orientation`: ✅
* `Hide display cutout`: ✅
* `Keep Screen On`: ✅
* `Touchscreen input mode`: Trackpad
* `Show stylus click option`: ❌
* `Capture external mouse when possible`: ❌
* `Enable tap-to-move for touchpads`: ❌
* `Show additional keyboard`: ❌
* `Show IME with external keyboard`: ❌
* `Prefer scancodes when possible`: ✅
* `Enable accessibility service for intercepting system shortcuts automatically`: ❌
Despues de terminada la instalación en Termux, tendran disponible un menu, tal como Termux-box original, donde tendran varias opciones de configuración.
En `preferences`, la configuración probada fue:
* `Resolution`: 1280x720
* `Locale`: es-AR
* `DYNAREC_BIGBLOCK`: 2
* `DYNAREC CONFIGURATION`: Better Performance (4)
* `Cores amount`: 4 (4-7)
* `Run services on startup`: enabled
* `Change box86/box64`: updated build
* `Custom Wine`: Wine-GE-proton-8.13 (opción 2)
Volver atrás y ejecutar `box64 wine64 with turnip dri3`, luego abrir Termux-X11
Una vez dentro, se instalará automáticamente `VCRedist 2008-2022` y `DotNet Desktop Framework 7.0`. De momento, la instalación no es visual, por lo que hay que revisar en la app `Taskmgr` (`Arranque/Start->Apps->taskmgr`), y ver que haya terminado de correr la instalación de DotNet para saber que ya ha terminado la instalación.
Una vez terminado, en `Arranque/Start->Install` se debe instalar lo siguiente:
* 1 - `dxvk-dev`
* 2 - `Turnip-a7xx-dri3`
* 3 - `mono-gecko`
Hecho esto, ya está completamente configurado este `MOD de Termux-box`. Ante cualquier error o duda, abrir `ISSUES` (cuando estén disponibles), o plantearlas en [Emutesting Discord](https://discord.com/invite/zGnEcUZgtF).
Pueden ver diferentes pruebas en [mi canal de YouTube](https://www.youtube.com/@EmuTesting)
#
Muchísimas Gracias Olegos2 por haber creado [Termux-box](https://github.com/olegos2/termux-box)! Realmente es una herramienta muy potente.
Y Gracias a los consejos de [MatiasEP](https://github.com/MatiasEP) y Mr. Purple
## Device support
### Android
* `Android 9+` — muy básico, puede no funcionar
* `Android 10+` — Solo root
* `Android 11+` — root/no-root
### Render
* Snapdragon con Adreno 6xx o Adreno 7xx — Turnip + Zink / Turnip + DXVK con mejor rendimiento.
* Qualcomm/Mediatek/Exynos — VirGL
## Features
* De momento, las updates de `Termux-box` no las pude aplicar en mi mod, pero es en lo que trabajaré ahora.
* TFM funciona mucho mejor con un custom wine.
* Rootfs AHORA NO TAN LIVIANO (4/5GB).
* `Proot`.
* `Chroot`.
* VirGL server con soporte dxtn. Mesa-VirGL 18.3.0, 19.1.8, 22.1.7.
* `Turnip` con soporte de adreno 610 y 7xx. `Mesa-zink-11.06.22` de alexvorxx que es más rápido y tiene mejor compatibilidad. `D8VK + DXVK + VKD3D` y `WineD3D`.
* `Prefix-tweaks` script que instala DirectX, 7-Zip, fixes de registro, mejor taskmgr y notepad. Tema personalizado, mejor fuente y mejores iconos. E:\ (Android/data/com.termux/files/Download) para mejor rendimiento sin tener que usar C:\
* `wine-tweaks` experimental que instala wine automáticamente, lo mejora para tener un mejor rendimiento en TFM y reduce su tamaño
* `zstd`, `gstream` y `winbind` para solucionar algunos errores que impiden que, por ejemplo, RE7 no pase de la pantalla de título.
* Instaladores de `VCRedist desde 2008 a 2022` y `.Net Desktop Framework 7.0` para correcta instalación de EasyAntiCheat (Aún no se pudo probar que funcione correctamente)
## Third party applications
[Box64](https://github.com/ptitSeb/box64) MIT license
[Box86](https://github.com/ptitSeb/box86) MIT license
[Proot](https://github.com/termux/proot) GPL-2.0 license
[DXVK](https://github.com/doitsujin/dxvk) Zlib license
[DXVK-ASYNC](https://github.com/Sporif/dxvk-async)
[DXVK-GPLASYNC](https://gitlab.com/Ph42oN/dxvk-gplasync)
[VKD3D](https://github.com/lutris/vkd3d) LGPL-2.1 license
[D8VK](https://github.com/AlpyneDreams/d8vk) Zlib license
[Termux-app](https://github.com/termux/termux-app) GPLv3 license
[Termux-x11](https://github.com/termux/termux-x11) GPL-3.0 license
[Wine](https://wiki.winehq.org/Licensing)
[Mesa](https://docs.mesa3d.org/license.html) MIT license
[mesa-zink-11.06.22](https://github.com/alexvorxx/mesa-zink-11.06.22)
|
'use client'
import React, { useRef, useEffect } from 'react'
import s from './HorizontalScrollContainer.module.scss'
type HorizontalScrollContainerProps = {
children: React.ReactNode
}
const HorizontalScrollContainer: React.FC<HorizontalScrollContainerProps> = ({
children,
}) => {
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const handleResize = () => {
const container = containerRef.current
if (container?.scrollWidth && container?.clientWidth) {
if (container.scrollWidth > container.clientWidth) {
container.classList.add(s.scrollable)
} else {
container.classList.remove(s.scrollable)
}
}
}
window.addEventListener('resize', handleResize)
handleResize()
return () => {
window.removeEventListener('resize', handleResize)
}
}, [])
return (
<div ref={containerRef} className={`${s.horizontalScrollContainer} `}>
{children}
</div>
)
}
export default HorizontalScrollContainer
|
import { Button, Card } from "react-bootstrap";
import { HiOutlineLocationMarker } from "react-icons/hi";
import { BsCalendar3 } from "react-icons/bs";
import { BsInfoCircle } from "react-icons/bs";
import { BsQrCode } from "react-icons/bs";
import { BsPeopleFill } from "react-icons/bs";
import "./CardEvent.scss"
import { Link } from "react-router-dom";
export function CardEvent(props) {
const { image, title, startDate, endDate, location, info, className, onClickFunction, onClickFunctionDois, idEvento, agenda } = props
return (
<Card className={`card-event ${className}`}>
<div className="card-event-thumb-container">
<Card.Img src={image} className="card-event-img" />
</div>
<div className="card-event-thumb-footer">
<div className="card-event-header">
<span className="card-event-title">
<strong>{title}</strong>
</span>
{info && (
<div className="d-flex">
<Button className="info-card-evento"
onClick={onClickFunction}
style={{ backgroundColor: "transparent", border: "none" }}
>
<BsInfoCircle className="card-icon-b" size={20}/>
</Button>
<Button className="info-card-evento"
onClick={onClickFunctionDois}
style={{ backgroundColor: "transparent", border: "none" }}
>
<BsQrCode className="card-icon-b" size={20}/>
</Button>
<Button className="info-card-evento"
style={{ backgroundColor: "transparent", border: "none" }}
>
<Link to={`/participantes/listar/${idEvento}`}> <BsPeopleFill className="card-icon-b" size={20}/></Link>
</Button>
<Button className="info-card-evento"
style={{ backgroundColor: "transparent", border: "none" }}
>
<Link to={`/agenda/${idEvento}`}> <BsCalendar3 className="card-icon-b" size={20}/></Link>
</Button>
</div>
)}
{agenda && (
<div className="d-flex">
<Button className="info-card-evento"
style={{ backgroundColor: "transparent", border: "none" }}
>
<Link to={`/agenda/${idEvento}`}> <BsCalendar3 className="card-icon-b" size={20}/></Link>
</Button>
</div>
)}
</div>
<div className="card-event-info-thumb mt-3">
{startDate && endDate && (
<span className="info-card-evento">
<BsCalendar3 className="card-icon-a" size={20}/> {startDate} - {endDate}
</span>
)}
{location && (
<span className="info-card-evento">
<HiOutlineLocationMarker className="card-icon-b" size={20}/> {location}
</span>
)}
</div>
</div>
</Card>
);
}
|
import { useNavigation } from "@react-navigation/native";
import { MapPin, Star } from "phosphor-react-native";
import { View, Text, Image, TouchableOpacity } from "react-native";
import { urlFor } from "../../sanity";
interface RestaurantCard {
id: number;
bannerUrl: string;
token: string;
title: string;
rating: number;
genre: string;
address: string;
short_description: string;
dishes: [];
long: number;
lat: number;
}
export function RestaurantCard({
id,
bannerUrl,
title,
token,
rating,
genre,
address,
short_description,
dishes,
long,
lat,
}: RestaurantCard) {
const navigation = useNavigation();
return (
<TouchableOpacity
onPress={() => {
navigation.navigate("Restaurant", {
id,
token,
bannerUrl,
title,
rating,
genre,
address,
short_description,
dishes,
long,
lat,
});
}}
className="bg-white mr-3 shadow-sm"
>
<Image
source={{
uri: urlFor(bannerUrl).url(),
}}
className="h-36 w-64 rounded-xl"
/>
<View className="px-3 pb-4">
<Text className="font-bold text-xl text-gray-600 pt-2">{title}</Text>
<View className="flex-row items-center space-x-1">
<Star
style={{ opacity: 0.5 }}
weight="fill"
color="green"
size={22}
/>
<Text className="text-xs text-gray-500">
<Text className="text-green-500">{rating}</Text> · {genre}
</Text>
</View>
<View className="flex-row items-center mt-2 space-x-1">
<MapPin style={{ opacity: 0.5 }} color="gray" size={22} />
<Text className="text-xs text-gray-500">Próximo · {address}</Text>
</View>
</View>
</TouchableOpacity>
);
}
|
import { useState } from 'react';
import {FiSearch} from 'react-icons/fi';
import {BsFiletypePdf} from 'react-icons/bs';
import clientesPDF from './Reports/Clientes/Clientes';
import './style.css';
import api from './services/api';
function App() {
const [input, setInput] = useState('');
const [cep, setCep] = useState('');
async function handleSourch (){
if (input === ''){
alert("Preencha algum CEP")
return;
}
try{
const response = await api.get(`${input}/json`);
setCep(response.data)
setInput("");
}catch{
alert("Erro ao buscar CEP!");
setInput("")
}
}
return (
<div className="container">
<h1 className="title">Buscador CEP</h1>
<div className="containerInput">
<input
type="text"
placeholder="Digite seu CEP.."
value={input}
onChange={(e) => setInput(e.target.value) }/>
<button className="buttonSearch" onClick={handleSourch}>
<FiSearch size={25} color='#FFF'/>
</button>
</div>
{/* area para depois que buscado o CEP apareça as informações */}
{Object.keys(cep).length > 0 && (
<main className='main'>
<h2>CEP: {cep.cep}</h2>
<span>{cep.logradouro}</span>
<span>{cep.complemento}</span>
<span>{cep.bairro}</span>
<span>{cep.localidade} - {cep.uf}</span>
</main>
)};
<button className="buttonPDF" onClick={(e) => cep && clientesPDF(cep)}>
<BsFiletypePdf size={30} color='#FFF'/>
</button>
</div>
);
}
export default App;
|
const mongoose = require('mongoose');
const { Schema } = mongoose;
const ItemSchema = new Schema({
name: { type: String, required: true, minLength: 4, maxLength: 100 },
description: { type: String, required: true, minLength: 10, maxLength: 500 },
category: [{ type: Schema.ObjectId, ref: 'Category', required: true }],
price: {
type: Number,
required: true,
min: 0.01,
validate: {
validator(value) {
const decimalPlaces = (value.toString().split('.')[1] || '').length;
return Number.isFinite(value) && decimalPlaces === 2;
},
message: 'Price must be a float with 1 decimal places.',
},
},
numberInStock: {
type: Number,
required: true,
validate: {
validator(value) {
return Number.isInteger(value) && value >= 0;
},
message: 'Number in stock must be an integer.',
},
},
});
ItemSchema.virtual('url').get(function () {
return `/products/${this._id}`;
});
module.exports = mongoose.model('Item', ItemSchema);
// Item: name, description, category,
// price, number in stock, URL
|
/**
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.*;
import java.security.SecureRandom;
import java.util.*;
public class Paillier_GUI implements ActionListener {
static Paillier_GUI paillier_GUI = new Paillier_GUI();
private static final int KEY_SIZE = 512;
private static JPanel jPanel;
private static JFrame jFrame;
private static JLabel jLabel0, jLabel1,jLabel2;
private static JButton button1,button2, button3, button4, button5, button6, button7, button8, button9;
private static JTextField jTextField1, jTextField2, jTextField3, jTextField4, jTextField5, jTextField6, jTextField7, jTextField8, jTextField9, jTextField10, jTextField11;
BigInteger m1, m2, em1, em2, product_em1em2, sum_m1m2, prod_m1m2, expo_em1m2;
/**
* p and q are two large primes.
* lambda = lcm(p-1, q-1) = (p-1)*(q-1)/gcd(p-1, q-1).
*/
private BigInteger p, q, lambda;
/**
* n = p*q, where p and q are two large primes.
*/
public BigInteger n;
/**
* nsquare = n*n
*/
public BigInteger nsquare;
/**
* a random integer in Z*_{n^2} where gcd (L(g^lambda mod n^2), n) = 1.
*/
private BigInteger g;
/**
* number of bits of modulus
*/
private int bitLength;
/**
* Constructs an instance of the Paillier_GUI cryptosystem.
* @param bitLengthVal number of bits of modulus
* @param certainty The probability that the new BigInteger represents a prime number will exceed (1 - 2^(-certainty)). The execution time of this constructor is proportional to the value of this parameter.
*/
public Paillier_GUI(int bitLengthVal, int certainty) {
KeyGeneration(bitLengthVal, certainty);
}
/**
* Constructs an instance of the Paillier_GUI cryptosystem with 512 bits of modulus and at least 1-2^(-64) certainty of primes generation.
*/
public Paillier_GUI() {
KeyGeneration(512, 64);
}
/**
* Sets up the public key and private key.
* @param bitLengthVal number of bits of modulus.
* @param certainty The probability that the new BigInteger represents a prime number will exceed (1 - 2^(-certainty)). The execution time of this constructor is proportional to the value of this parameter.
*/
public void KeyGeneration(int bitLengthVal, int certainty) {
bitLength = bitLengthVal;
/*Constructs two randomly generated positive BigIntegers that are probably prime, with the specified bitLength and certainty.*/
p = new BigInteger(bitLength / 2, certainty, new Random());
q = new BigInteger(bitLength / 2, certainty, new Random());
n = p.multiply(q);
nsquare = n.multiply(n);
g = new BigInteger("2");
lambda = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)).divide(
p.subtract(BigInteger.ONE).gcd(q.subtract(BigInteger.ONE)));
/* check whether g is good.*/
if (g.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).gcd(n).intValue() != 1) {
System.out.println("g is not good. Choose g again.");
System.exit(1);
}
}
/**
* Encrypts plaintext m. ciphertext c = g^m * r^n mod n^2. This function explicitly requires random input r to help with encryption.
* @param m plaintext as a BigInteger
* @param r random plaintext to help with encryption
* @return ciphertext as a BigInteger
*/
public BigInteger Encryption(BigInteger m, BigInteger r) {
return g.modPow(m, nsquare).multiply(r.modPow(n, nsquare)).mod(nsquare);
}
/**
* Encrypts plaintext m. ciphertext c = g^m * r^n mod n^2. This function automatically generates random input r (to help with encryption).
* @param m plaintext as a BigInteger
* @return ciphertext as a BigInteger
*/
public BigInteger Encryption(BigInteger m) {
BigInteger r = new BigInteger(bitLength, new Random());
return g.modPow(m, nsquare).multiply(r.modPow(n, nsquare)).mod(nsquare);
}
/**
* Decrypts ciphertext c. plaintext m = L(c^lambda mod n^2) * u mod n, where u = (L(g^lambda mod n^2))^(-1) mod n.
* @param c ciphertext as a BigInteger
* @return plaintext as a BigInteger
*/
public BigInteger Decryption(BigInteger c) {
BigInteger u = g.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).modInverse(n);
return c.modPow(lambda, nsquare).subtract(BigInteger.ONE).divide(n).multiply(u).mod(n);
}
/**
* main function
* @param str intput string
*/
public static void main(String[] str) {
/* instantiating an object of Paillier_GUI cryptosystem*/
/* instantiating two plaintext msgs*/
jPanel = new JPanel();
jFrame = new JFrame();
jFrame.setSize(450,300);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.add(jPanel);
jPanel.setLayout(null);
jLabel0 = new JLabel("Paillier Homomorphic Encryption");
jLabel0.setBounds(130,5,280,20);
jPanel.add(jLabel0);
jLabel1 = new JLabel("m1 = ");
jLabel1.setBounds(10,30,50,20);
jPanel.add(jLabel1);
jTextField1 = new JTextField(20);
jTextField1.setBounds(60,30,150,20);
jPanel.add(jTextField1);
jLabel2 = new JLabel("m2 = ");
jLabel2.setBounds(230,30,50,20);
jPanel.add(jLabel2);
jTextField2 = new JTextField(20);
jTextField2.setBounds(280,30,150,20);
jPanel.add(jTextField2);
button1 = new JButton("Encrypt m1");
button1.setBounds(10,50,150,20);
button1.addActionListener(new Paillier_GUI());
jPanel.add(button1);
jTextField3 = new JTextField(20);
jTextField3.setBounds(180,50,250,20);
jPanel.add(jTextField3);
button2 = new JButton("Encrypt m2");
button2.setBounds(10,70,150,20);
button2.addActionListener(new Paillier_GUI());
jPanel.add(button2);
jTextField4 = new JTextField(20);
jTextField4.setBounds(180,70,250,20);
jPanel.add(jTextField4);
button3 = new JButton("Decrypt m1");
button3.setBounds(10,90,150,20);
button3.addActionListener(new Paillier_GUI());
jPanel.add(button3);
jTextField5 = new JTextField(20);
jTextField5.setBounds(180,90,250,20);
jPanel.add(jTextField5);
button4 = new JButton("Decrypt m2");
button4.setBounds(10,110,150,20);
button4.addActionListener(new Paillier_GUI());
jPanel.add(button4);
jTextField6 = new JTextField(20);
jTextField6.setBounds(180,110,250,20);
jPanel.add(jTextField6);
button5 = new JButton("em1*em2");
button5.setBounds(10,130,150,20);
button5.addActionListener(new Paillier_GUI());
jPanel.add(button5);
jTextField7 = new JTextField(20);
jTextField7.setBounds(180,130,250,20);
jPanel.add(jTextField7);
button6 = new JButton("Sum m1+m2");
button6.setBounds(10,150,150,20);
button6.addActionListener(new Paillier_GUI());
jPanel.add(button6);
jTextField8 = new JTextField(20);
jTextField8.setBounds(180,150,250,20);
jPanel.add(jTextField8);
button7 = new JButton("Decrypted Sum");
button7.setBounds(10,170,150,20);
button7.addActionListener(new Paillier_GUI());
jPanel.add(button7);
jTextField9 = new JTextField(20);
jTextField9.setBounds(180,170,250,20);
jPanel.add(jTextField9);
button8 = new JButton("Product m1*m2");
button8.setBounds(10,190,150,20);
button8.addActionListener(new Paillier_GUI());
jPanel.add(button8);
jTextField10 = new JTextField(20);
jTextField10.setBounds(180,190,250,20);
jPanel.add(jTextField10);
button9 = new JButton("Decrypted Product");
button9.setBounds(10,210,150,20);
button9.addActionListener(new Paillier_GUI());
jPanel.add(button9);
jTextField11 = new JTextField(20);
jTextField11.setBounds(180,210,250,20);
jPanel.add(jTextField11);
jFrame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
m1 = new BigInteger(jTextField1.getText());
em1 = paillier_GUI.Encryption(m1);
jTextField3.setText(em1.toString());
}
if(e.getSource() == button2) {
m2 = new BigInteger(jTextField2.getText());
em2 = paillier_GUI.Encryption(m2);
jTextField4.setText(em2.toString());
}
if(e.getSource() == button3) {
em1 = new BigInteger(jTextField3.getText());
jTextField5.setText(paillier_GUI.Decryption(em1).toString());
}
if(e.getSource() == button4) {
em2 = new BigInteger(jTextField4.getText());
jTextField6.setText(paillier_GUI.Decryption(em2).toString());
}
if(e.getSource() == button5) {
em1 = new BigInteger(jTextField3.getText());
em2 = new BigInteger(jTextField4.getText());
product_em1em2 = em1.multiply(em2).mod(paillier_GUI.nsquare);
jTextField7.setText(product_em1em2.toString());
}
if(e.getSource() == button6) {
m1 = new BigInteger(jTextField1.getText());
m2 = new BigInteger(jTextField2.getText());
sum_m1m2 = m1.add(m2).mod(paillier_GUI.n);
jTextField8.setText(sum_m1m2.toString());
}
if(e.getSource() == button7) {
product_em1em2 = new BigInteger(jTextField7.getText());
jTextField9.setText(paillier_GUI.Decryption(product_em1em2).toString());
}
if(e.getSource() == button8) {
m1 = new BigInteger(jTextField1.getText());
m2 = new BigInteger(jTextField2.getText());
prod_m1m2 = m1.multiply(m2).mod(paillier_GUI.n);
jTextField10.setText(prod_m1m2.toString());
}
if(e.getSource() == button9) {
em1 = new BigInteger(jTextField3.getText());
m2 = new BigInteger(jTextField2.getText());
expo_em1m2 = em1.modPow(m2, paillier_GUI.nsquare);
jTextField11.setText(paillier_GUI.Decryption(expo_em1m2).toString());
}
}
}
|
import React from "react";
import PropTypes from "prop-types";
import css from "./select.module.scss";
class Select extends React.Component {
static propTypes = {
confirmationMessage: PropTypes.string,
defaultValue: PropTypes.string,
label: PropTypes.string,
name: PropTypes.string,
onChange: PropTypes.func,
requireConfirmation: PropTypes.bool,
values: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string,
value: PropTypes.string
})
).isRequired
};
static defaultProps = {
onChange: () => {}
};
state = {};
componentDidMount() {
this.setState({
selectedValue: this.select.value,
selectedLabel: this.getLabel(this.select.value)
});
}
getLabel = value => {
return this.props.values.reduce((accum, item) => {
if (item.value === value) {
return item.label;
} else {
return accum;
}
}, "");
};
onChange = e => {
if (
this.props.requireConfirmation &&
!confirm(this.props.confirmationMessage)
) {
this.select.value = this.state.selectedValue;
} else {
const value = e.currentTarget.value;
this.setState({
selectedValue: value,
selectedLabel: this.getLabel(value)
});
this.props.onChange(value);
}
};
render() {
const label = this.props.label ? `${this.props.label}:` : "";
return (
<div className={css.select}>
<label htmlFor="select">{`${label} ${this.state.selectedLabel}`}</label>
<select
defaultValue={this.props.defaultValue}
id="select"
name={this.props.name}
onChange={this.onChange}
ref={s => (this.select = s)}
>
{this.props.values.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</div>
);
}
}
export default Select;
|
import { Collider } from '../Collider';
import { gameResourses } from '../Resources';
import { GameResourses } from '../Resources/types';
import { SceneManager } from '../SceneManager';
import { Add } from './Add';
import { defaultGameConfig } from './defaultGameConfig';
import { TimeStep } from './TimeStep/TimeStep';
import { GameBoundsProps, GameConfig } from './types';
export class Game {
private loop: TimeStep;
private contextValue: CanvasRenderingContext2D | null;
public get context() {
if (this.contextValue === null) {
throw new Error('Context is null');
}
return this.contextValue;
}
public parent: Element | null;
public isRunning: boolean;
public canvas: HTMLCanvasElement | null;
public scene: SceneManager;
public bgColor: string;
public width: number;
public height: number;
public collider: Collider;
public add: Add = new Add(this);
public res: GameResourses;
public score: number;
constructor(config: GameConfig, cb: (score: number) => void) {
const { width, height, parent, backgroundColor } = config;
this.width = width ?? defaultGameConfig.width;
this.height = height ?? defaultGameConfig.height;
this.bgColor = backgroundColor ?? defaultGameConfig.backgroundColor;
this.parent = this.getParent(parent ?? defaultGameConfig.parent);
this.isRunning = false;
this.loop = new TimeStep(this);
this.canvas = null;
this.contextValue = null;
this.add = new Add(this);
this.res = gameResourses;
this.scene = new SceneManager(this, config.scenes, cb);
this.collider = new Collider(this);
this.score = 0;
this.create();
}
public start() {
this.isRunning = true;
this.loop.start();
}
private create() {
this.createCanvas();
this.renderCanvas();
this.start();
}
private getParent(parent: string | HTMLElement) {
return parent instanceof HTMLElement ? parent : document.querySelector(parent);
}
private createCanvas() {
const canvas: HTMLCanvasElement = document.createElement('canvas');
canvas.height = this.height;
canvas.width = this.width;
canvas.style.backgroundColor = this.bgColor;
this.canvas = canvas;
this.contextValue = canvas.getContext('2d');
}
private renderCanvas() {
if (this.parent && this.canvas) {
this.parent.appendChild(this.canvas);
}
}
public exit() {}
public update(delay: number) {
if (this.isRunning && this.scene.current) {
this.scene.current.update(delay);
}
}
public render() {
this.context.clearRect(0, 0, this.width, this.height);
this.scene.current?.render();
}
/** get game area bounds with object padding */
getGameArea(props: GameBoundsProps) {
const { paddingTop = 0, paddingRight = 0, paddingBottom = 0, paddingLeft = 0 } = props;
const xStart = paddingLeft;
const yStart = paddingTop;
const xEnd = this.width - paddingRight;
const yEnd = this.height - paddingBottom;
return { xStart, yStart, xEnd, yEnd };
}
/** is object in game area */
isOnGameArea(props: GameBoundsProps) {
const { x, y } = props;
const gameArea = this.getGameArea(props);
const { xStart, yStart, xEnd, yEnd } = gameArea;
return x > xStart && y > yStart && x < xEnd && y < yEnd;
}
/** is object on bounds of game area */
isOnGameBounds(props: GameBoundsProps) {
const { x, y } = props;
const gameArea = this.getGameArea(props);
const { xStart, yStart, xEnd, yEnd } = gameArea;
return {
isOnLeft: x <= xStart,
isOnRight: x >= xEnd,
isOnBottom: y >= yEnd,
isOnTop: y <= yStart,
};
}
}
|
'// CheckInserts.bas
'//------------------------------------------------------------------
'// CheckInserts - Check target COA sheet(s) for insertion available.
'// 7/3/20. wmk.
'//------------------------------------------------------------------
public function CheckInserts(psMonth As String, psAcct1 As String,_
psAcct2 As String, rpoCat1Range As Object, rpoCat2Range As Object) as Integer
'// Usage. iVal = CheckInserts(sMonth, sAcct1, sAcct2, oCat1Range, oCat2Range)
'//
'// sMonth = Month name string (e.g. "January")
'// sAcct1 = COA from 1st line of transaction
'// sAcct2 = COA from 2nd line of transaction
'// rpoCat1Range = (returned)
'// rpoCat2Range = (returned)
'//
'// Entry. Spreadsheet has category sheets for all possible COA #s
'//
'// Exit. rplIns1Ptr = row for insertion of line 1 transaction
'// rplIns2Ptr = row for insertion of line 2 transaction
'//
'// Calls. GetInsRow.
'//
'// Modification history.
'// ---------------------
'// 6/1/20. wmk. original code; stub
'// 6/2/20. wmk. code transported from within PlaceTransM; error handling
'// set up
'// 6/8/20. wmk. bug fix where sCOA1Msg and sCOA2Msg not declared
'// 7/3/20. wmk. bug fix in error handling using lGLCurrRow, needs lErrRow
'//
'// Notes. Passed paramters are COA #s; they will be used to access the
'// correct account catgory sheets, for the month of the transaction
'//
'// constants.
'// insert error codes.
const ERRCOANOTFOUND=-1
const ERROUTOFROOM=-2
const ERRNOCOAMONTH=-3
const sERRCOANOTFOUND="ERRCOANOTFOUND"
const sERROUTOFROOM="ERROUTOFROOM"
const sERRNOCOAMONTH="ERRNOCOAMONTH"
const sERRUNKNOWN="ERRUNKNOWN"
'//----------in Module error handling setup-------------------------------
'// LogError setup snippet.
const csERRUNKNOWN="ERRUNKNOWN"
const sMyName="CheckInserts"
'// add additional error code strings here...
Dim sErrName as String '// error name for LogError
Dim sErrMsg As String '// error message for LogError
'//*---------error handling setup---------------------------
'// ErrLogGetModule() - get current module name gsErrModule
'// ErrLogSetModule(sName) - set current module name gsErrModule
'// ErrLogGetCellInfo(lColumn, lRow) - get error focus cell column, row
'// ErrLogSetCellInfo(lColumn, lRow) - set error focus cell column, row
'// ErrLogGetSheet - Get sheet index from error log globals.
'// ErrLogSetSheet - Set sheet index in error log globals.
dim iErrSheetIx as Integer
dim lErrColumn as Long
dim lErrRow as Long
dim sErrCurrentMod As String
'//----------end in Module error handling setup---------------------------
'// process control constants.
const ERRCONTINUE=-1 '// error, but continue with next transaction
const ERRSTOP=-2 '// error, stop processing transactions
'// local variables.
dim iRetValue As Integer '// function returned value
dim sMonth As String '// local month
'// Object setup variables.
dim oDoc As Object '// ThisComponent
dim oSheets As Object '// Doc.getSheets()
'// COA Sheet processing variables.
dim sAcct As String '// first line COA#
dim sAcctB As String '// second line COA#
dim sAcctCat1 as String '// accounting category of 1st line of transaction
dim sAcctCat2 as String '// account category of 2nd line of transaction
dim bSameAcctCat as boolean '// account categories the same flag
dim oCat1Sheet As Object '// COA sheet for 1st transaction line
dim oCat2Sheet As Object '// COA sheet for 2nd transaction line
dim bSameCOA As Boolean '// COAs match flag
dim lCat1InsRow As Long '// COA sheet insertion row, line 1
dim lCat2InsRow As Long '// COA sheet insertion row, line 2
dim sBadCOA As String '// first COA bad string
dim sBadCOA2 As String '// second COA bad string
dim iStatus As Integer '// processing status flag
dim sCOA1Msg As String '// COA1 error message string
dim sCOA2Msg As String '// COA2 error message string
'// code.
iRetValue = 0
iStatus = 0 '// clear general status
' rplIns1Ptr = -1 '// set bad pointers for return
' rplIns2Ptr = -1
sMonth = psMonth '// set local copy of passed month
'//*------------error handling code initialization---------------
'// preserve entry error settings.
iErrSheetIx = ErrLogGetSheet()
ErrLogGetCellInfo(lErrColumn, lErrRow)
sErrCurrentMod = ErrLogGetModule()
'//*
'// set local error settings.
ErrLogSetModule(sMyName)
'// keep entry sheet/cell selctions, since errors will be in GL
' ErrLogSetSheet(poTransRange.Sheet)
' ErrLogSetCellInfo(COLDATE, poTransRange.StartRow)
ErrLogSetRecording(true) '// enable log entries
'//*----------end error handling code initialization-------------
CheckInserts = iRetValue
' if true then
' Exit Function
' endif
'//---------------end stub code--------------------
'//-----------------CheckInserts code starts here----------------------------------------
'//
'// Usage. iVal = CheckInserts(psMonth, psAcct1, psAcct2, rplIns1Ptr, rplIns2Ptr)
'//
'// psMonth = Month name string (e.g. "January")
'// psAcct1 = COA from 1st line of transaction
'// psAcct2 = COA from 2nd line of transaction
'// rplIns1Ptr = (returned)
'// rplIns2Ptr = (returned)
'//
'// get appropriate sheet names from COA account numbers
iStatus = 0 '// clear processing exceptions
sAcct = psAcct1 '// copy COAs to local vars
sAcctB = psAcct2
sAcctCat1 = GetTransSheetName(sAcct)
sAcctCat2 = GetTransSheetName(sAcctB)
bSameAcctCat = (StrComp(sAcctCat1, sAcctCat2) = 0)
dim iBrkpt As Integer
iBrkpt = 1
'// set up oCat1Sheet as sheet object for first half of transaction
'// oCat2Sheet as sheet object for second half of transaction
'static oCat1Sheet as Object '// account sheet object of 1st category in transaction
'static oCat2Sheet as Object '// account sheet object of 2nd category in transaction
'dim lCat1InsRow as long '// insert index for 1st category in transaction
'dim lCat2InsRow as long '// insert index for 2nd cateory in transaction
'XRay Doc
oDoc = ThisComponent
oSheets = oDoc.getSheets()
'XRay oSheets
'// check if same sheet, and just copy instance '// mod051920
oCat1Sheet = oSheets.getByName(sAcctCat1)
if bSameAcctCat then
oCat2Sheet = oCat1Sheet
else
oCat2Sheet = oSheets.getByName(sAcctCat2)
endif
rpoCat1Range.Sheet = oCat1Sheet.RangeAddress.Sheet
rpoCat2Range.Sheet = oCat2Sheet.RangeAddress.Sheet
'XRay oCat1Sheet
iBrkpt=1
'// check here if COA#s different; if not, will bail out later '// mod051920
bSameCOA = StrComp(sAcct, sAcctB) = 0 '// mod051920
lCat1InsRow = GetInsRow(oCat1Sheet, sAcct, sMonth) '// mod051920
if bSameCOA then '// mod051920
'// Note: might get away with setting same insertion row, since will
'// insert 2 lines... for now, skipped
lCat2InsRow = lCat1InsRow '// mod051920
else '// mod051920
lCat2InsRow = GetInsRow(oCat2Sheet, sAcctB, sMonth) '// mod051920
endif '// end same COA conditional '// mod051920
'// add code to verify have a row in each sheet before committing to change
'dim lBadRow1 as long '// 1st acct insert row return value
'dim lBadRow2 as lont '// 2nd acct insert row return value
if lCat1InsRow < 0 OR lCat2InsRow < 0 then
'// issue appropriate message and don't mark rows as processed
sBadCOA = ""
sBadCOA2 = ""
'// handle transaction line 1 error.
if lCat1InsRow < 0 then
sBadCOA = sAcct
sCOA1Msg = "" '// clear line 1 message
ErrLogSetSheet(oCat1Sheet.RangeAddress.Sheet)
ErrLogSetCellInfo(COLDATE, lErrRow)
Select Case lCat1InsRow
' Case -1
Case ERRCOANOTFOUND
sCOA1Msg = "Account "+sBadCOA+" not found"
sErrName = sERRCOANOTFOUND
' Case -2
Case ERROUTOFROOM
sCOA1Msg = "Account "+sBadCOA+" month "+sMonth+" not enough rows"_
+" to insert"
sErrName = sERROUTOFROOM
' Case -3
Case ERRNOCOAMONTH
sCOA1Msg = "Account "+sBadCOA+" month "+sMonth+" not found"
sErrName = sERRNOCOAMONTH
Case else
sCOA1Msg = "Account "+sBadCOA+"Undocumented error"
sErrName = sERRUNKNOWN
end Select
sErrMsg = sCOA1Msg
Call LogError(sErrName, sErrMsg)
endif '// end error in 1st line conditional
if lCat2InsRow < 0 then
sBadCOA2 = sAcctB
sCOA2Msg = "" '// clear line 2 message
Select Case lCat2InsRow
' Case -1
Case ERRCOANOTFOUND
sCOA2Msg = "Account "+sBadCOA2+" not found"
sErrName = sERRCOANOTFOUND
' Case -2
Case ERROUTOFROOM
sCOA2Msg = "Account "+sBadCOA2+" month "+sMonth+" not enough rows"_
+" to insert"
sErrName = sERROUTOFROOM
' Case -3
Case ERRNOCOAMONTH
sCOA2Msg = "Account "+sBadCOA2+" month "+sMonth+" not found"
sErrName = sERRNOCOAMONTH
sCOA2Msg = "Account "+sBadCOA2+"Undocumented error"
sErrName = sERRUNKNOWN
end Select
sErrMsg = sCOA2Msg
Call LogError(sErrName, sErrMsg) '// log error and continue
endif '// end bad line 2 insert row conditional
iStatus = ERRCONTINUE '// flag error to continue with next transaction
' msgBox(sCOA1Msg+CHR(13)+CHR(10) + sCOA2Msg)
'// advance to next transaction
GoTo AdvanceTrans
endif '// end problem with either COA insert conditional
'// no problems, set returned insertion rows
' rplIns1Ptr = lCat1InsRow
' rplIns2Ptr = lCat2InsRow
rpoCat1Range.StartRow = lCat1InsRow
rpoCat2Range.StartRow = lCat2InsRow
rpoCat1Range.EndRow = lCat1InsRow
rpoCat2Range.EndRow = lCat2InsRow
rpoCat1Range.StartColumn = COLDATE
rpoCat2Range.StartColumn = COLDATE
rpoCat1Range.EndColumn = COLREF
rpoCat2Range.EndColumn = COLREF
AdvanceTrans:
'//*-----------------restore error handling for caller-----------
'// restore entry error settings.
ErrLogSetModule(sErrCurrentMod)
ErrLogSetSheet(iErrSheetIx)
ErrLogSetCellInfo(lErrColumn, lErrRow)
'//*----------end error handling setup---------------------------
'// iStatus = 0, no error
'// ERRCONTINUE (-1) - error; continue with next transaction
'// ERRSTOP (-2) - error; stop processing transactions
iRetValue = iStatus '// set returned status
CheckInserts = iRetValue
end function '// end CheckInserts 7/3/20
'/**/
|
package leetCode;
import java.util.*;
import java.util.stream.Collectors;
public class LongestSubString {
public static void main(String[] args) {
System.out.println("abcabcbb -> " + lengthOfLongestSubstring("abcabcbb"));
System.out.println("bbbbb -> " + lengthOfLongestSubstring("bbbbb"));
System.out.println("pwwkew -> " + lengthOfLongestSubstring("pwwkew"));
System.out.println("dvdf -> " + lengthOfLongestSubstring("dvdf"));
System.out.println("asjrgapa -> " + lengthOfLongestSubstring("asjrgapa"));
System.out.println("------------------------------");
System.out.println("abcabcbb -> " + lengthOfLongestSubstring2("abcabcbb"));
System.out.println("bbbbb -> " + lengthOfLongestSubstring2("bbbbb"));
System.out.println("pwwkew -> " + lengthOfLongestSubstring2("pwwkew"));
System.out.println("dvdf -> " + lengthOfLongestSubstring2("dvdf"));
System.out.println("asjrgapa -> " + lengthOfLongestSubstring2("asjrgapa"));
}
private static int lengthOfLongestSubstring(String s) {
List<Character> charList = s.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
HashMap<Integer, List<Character>> characterHashMap = new HashMap<>();
Integer flag = 0;
characterHashMap.put(flag, new ArrayList<>());
for (int i = 0; i < charList.size(); i++) {
for (int j = i; j <charList.size(); j++) {
if (characterHashMap.get(flag).isEmpty()) {
ArrayList<Character> objects = new ArrayList<>();
objects.add(charList.get(j));
characterHashMap.put(flag, objects);
} else if (!characterHashMap.get(flag).contains(charList.get(j))) {
characterHashMap.get(flag).add(charList.get(j));
}
}
flag++;
characterHashMap.put(flag, new ArrayList<>());
}
int max = 0;
for (Map.Entry<Integer, List<Character>> entry : characterHashMap.entrySet()) {
max = Math.max(max, entry.getValue().size());
}
return max;
}
private static int lengthOfLongestSubstring2(String s) {
Set<Character>set=new HashSet<>();
int maxLength=0;
int left=0;
for(int right=0;right<s.length();right++){
if(!set.contains(s.charAt(right))){
set.add(s.charAt(right));
maxLength=Math.max(maxLength,right-left+1);
}else{
while(s.charAt(left)!=s.charAt(right)){
set.remove(s.charAt(left));
left++;
}
set.remove(s.charAt(left));left++;
set.add(s.charAt(right));
}
}
return maxLength;
}
}
|
<template>
<v-card class="profile_reminder">
<v-row>
<v-col cols="4">
<div class="row">
<div class="mr-5">
<img class="avatar" src="../assets/icon/avatar.png" alt="avatar" />
</div>
<div class="column">
<div class="text-weight mb-2">
<h3>{{ userProfileData.name }}</h3>
</div>
<div class="text-weight">{{ textFilter('balance') }}:{{ config.unit }} {{ balanceSum | money }}</div>
</div>
</div>
</v-col>
<v-col cols="8">
<div class="row" style="flex-wrap: wrap">
<div
v-for="reminder in remindersArr"
:key="reminder"
class="pa-2 col-4 detail-wrap"
:class="reminders[reminder].class"
@click="reminders[reminder].func(reminders[reminder])"
>
<v-icon>{{ reminders[reminder].icon }}</v-icon>
{{ textFilter(reminders[reminder].title) }}
<div :class="`${getStatusColor(reminders[reminder].status)}--text cursior-pointer detail-text`">
{{ textFilter(reminders[reminder].statusTextMap[reminders[reminder].status]) }}
</div>
</div>
</div>
</v-col>
</v-row>
</v-card>
</template>
<script>
import { textFilter } from '@UTILS/i18n';
import { mapGetters, mapActions } from 'vuex';
export default {
name: 'ProfileReminder',
created() {
this.GET_USER_PROFILE();
this.GET_USER_BANK_LIST();
},
watch: {
isBankCardBinded: {
handler(v) {
this.reminders.bindCard.status = v;
},
immediate: true,
},
isMobileBinded: {
handler(v) {
this.reminders.bindMobile.status = v;
},
immediate: true,
},
isUserBaseDataOk: {
handler(v) {
this.reminders.base.status = v;
},
immediate: true,
},
},
data() {
return {
reminders: {
base: {
class: 'profile',
icon: 'person',
title: 'base',
status: 0,
statusTextMap: {
0: 'notOk',
1: 'ok',
},
func: () => {
this.$router.push('/userCentre/profile');
},
},
bindCard: {
class: 'bankCard',
icon: 'account_balance',
title: 'bindCard',
status: 0,
statusTextMap: {
0: 'notBinded',
1: 'binded',
},
func: () => {
this.$router.push('/userCentre/bankCard');
},
},
bindMobile: {
class: 'bindMobile',
icon: 'phone',
title: 'bindMobile',
status: 0,
statusTextMap: {
0: 'notBinded',
1: 'binded',
},
func: () => {
this.$router.push('/userCentre/profile');
},
},
pwdModify: {
class: 'pwdModify',
icon: 'vpn_key',
title: 'pwdModify',
status: 2,
statusTextMap: {
2: 'goToModify',
},
func: () => {
this.$router.push('/userCentre/loginPass');
},
},
goToWallet: {
class: 'checkWallet',
icon: 'account_balance_wallet',
title: 'checkWallet',
status: 2,
statusTextMap: {
2: 'goToSee',
},
func: () => {
this.$router.push('/userCentre/wallet');
},
},
goToNotification: {
class: 'noticeCenter',
icon: 'mail',
title: 'noticeCenter',
status: 2,
statusTextMap: {
2: 'goToSee',
},
func: () => {
this.$router.push('/userCentre/notice');
},
},
},
};
},
computed: {
...mapGetters(['config', 'balanceSum', 'userProfileData', 'userBankList']),
formatedBalanceSum() {
if (this.balanceSum) return `${this.config.unit}${this.balanceSum}`;
return '0.00';
},
remindersArr() {
return Object.keys(this.reminders);
},
isBankCardBinded() {
return this.userBankList.length > 0 ? 1 : 0;
},
isIdCardBinded() {
return !!this.userProfileData && this.userProfileData.cards.length > 0 ? 1 : 0;
},
isUserNameBinded() {
return !!this.userProfileData && this.userProfileData.username ? 1 : 0;
},
isMobileBinded() {
return !!this.userProfileData && this.userProfileData.mobile ? 1 : 0;
},
isUserBaseDataOk() {
return this.isIdCardBinded && this.isUserNameBinded && this.isMobileBinded ? 1 : 0;
},
},
methods: {
...mapActions(['GET_USER_PROFILE', 'GET_USER_BANK_LIST']),
getStatusColor(status) {
switch (status) {
case 0:
return 'error';
case 1:
return 'success';
case 2:
return 'primary';
default:
break;
}
},
textFilter(text) {
return textFilter(text, 'g_com_profileReminder_');
},
},
};
</script>
<style lang="scss" scoped>
.profile_reminder {
padding: 30px;
.row {
display: flex;
align-items: center;
}
.column {
display: flex;
flex-direction: column;
}
.detail-wrap {
min-width: 188px;
}
.detail-text {
margin: 10px 0px 0px 30px;
}
.text-weight {
font-weight: bold;
}
.avatar {
width: 100%;
max-width: 70px;
border-radius: 50%;
}
.cursior-pointer {
cursor: pointer;
&:hover {
color: var(--v-success-secondary) !important;
}
}
}
</style>
|
!--------------------------------------------------------------------------------------------------!
! CP2K: A general program to perform molecular dynamics simulations !
! Copyright (C) 2000 - 2018 CP2K developers group !
!--------------------------------------------------------------------------------------------------!
! **************************************************************************************************
!> \brief Handles all functions related to the CELL
!> \par History
!> 11.2008 Teodoro Laino [tlaino] - deeply cleaning cell_type from units
!> 10.2014 Moved many routines to cell_types.F.
!> \author Matthias KracK (16.01.2002, based on a earlier version of CJM, JGH)
! **************************************************************************************************
MODULE cell_methods
USE cell_types, ONLY: &
cell_clone, cell_create, cell_sym_none, cell_type, get_cell, init_cell, set_cell_param, &
use_perd_none, use_perd_x, use_perd_xy, use_perd_xyz, use_perd_xz, use_perd_y, &
use_perd_yz, use_perd_z
USE cp_log_handling, ONLY: cp_get_default_logger,&
cp_logger_type
USE cp_output_handling, ONLY: cp_print_key_finished_output,&
cp_print_key_unit_nr
USE cp_para_types, ONLY: cp_para_env_type
USE cp_parser_methods, ONLY: parser_get_next_line
USE cp_parser_types, ONLY: cp_parser_type,&
parser_create,&
parser_release
USE cp_units, ONLY: cp_unit_from_cp2k,&
cp_unit_to_cp2k
USE input_constants, ONLY: do_cell_cp2k,&
do_cell_xsc
USE input_cp2k_subsys, ONLY: create_cell_section
USE input_enumeration_types, ONLY: enum_i2c,&
enumeration_type
USE input_keyword_types, ONLY: keyword_get,&
keyword_type
USE input_section_types, ONLY: &
section_get_keyword, section_release, section_type, section_vals_get, &
section_vals_get_subs_vals, section_vals_type, section_vals_val_get, section_vals_val_set, &
section_vals_val_unset
USE kinds, ONLY: default_path_length,&
default_string_length,&
dp
USE mathconstants, ONLY: degree
USE mathlib, ONLY: angle
#include "./base/base_uses.f90"
IMPLICIT NONE
PRIVATE
CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'cell_methods'
! Public subroutines
PUBLIC :: read_cell, write_cell
CONTAINS
! **************************************************************************************************
!> \brief ...
!> \param cell ...
!> \param cell_ref ...
!> \param use_ref_cell ...
!> \param cell_section ...
!> \param check_for_ref ...
!> \param para_env ...
!> \par History
!> 03.2005 created [teo]
!> \author Teodoro Laino
! **************************************************************************************************
RECURSIVE SUBROUTINE read_cell(cell, cell_ref, use_ref_cell, cell_section, &
check_for_ref, para_env)
TYPE(cell_type), POINTER :: cell, cell_ref
LOGICAL, INTENT(OUT), OPTIONAL :: use_ref_cell
TYPE(section_vals_type), OPTIONAL, POINTER :: cell_section
LOGICAL, INTENT(IN), OPTIONAL :: check_for_ref
TYPE(cp_para_env_type), POINTER :: para_env
CHARACTER(len=*), PARAMETER :: routineN = 'read_cell', routineP = moduleN//':'//routineN
INTEGER :: my_per
INTEGER, DIMENSION(:), POINTER :: multiple_unit_cell
LOGICAL :: cell_read_a, cell_read_abc, cell_read_b, &
cell_read_c, cell_read_file, check, &
my_check
REAL(KIND=dp), DIMENSION(:), POINTER :: cell_angles, cell_par
TYPE(section_vals_type), POINTER :: cell_ref_section
my_check = .TRUE.
NULLIFY (cell_ref_section, cell_par, multiple_unit_cell)
IF (.NOT. ASSOCIATED(cell)) CALL cell_create(cell)
IF (.NOT. ASSOCIATED(cell_ref)) CALL cell_create(cell_ref)
IF (PRESENT(check_for_ref)) my_check = check_for_ref
cell%deth = 0.0_dp
cell%orthorhombic = .FALSE.
cell%perd(:) = 1
cell%symmetry_id = cell_sym_none
cell%hmat(:, :) = 0.0_dp
cell%h_inv(:, :) = 0.0_dp
cell_read_file = .FALSE.
cell_read_a = .FALSE.
cell_read_b = .FALSE.
cell_read_c = .FALSE.
! Trying to read cell info from file
CALL section_vals_val_get(cell_section, "CELL_FILE_NAME", explicit=cell_read_file)
IF (cell_read_file) CALL read_cell_from_external_file(cell_section, para_env)
! Trying to read cell info from the separate A, B, C vectors
! If cell information is provided through file A,B,C contain the file information..
! a print warning is shown on screen..
CALL section_vals_val_get(cell_section, "A", explicit=cell_read_a)
IF (cell_read_a) THEN
CALL section_vals_val_get(cell_section, "A", r_vals=cell_par)
cell%hmat(:, 1) = cell_par(:)
END IF
CALL section_vals_val_get(cell_section, "B", explicit=cell_read_b)
IF (cell_read_b) THEN
CALL section_vals_val_get(cell_section, "B", r_vals=cell_par)
cell%hmat(:, 2) = cell_par(:)
END IF
CALL section_vals_val_get(cell_section, "C", explicit=cell_read_c)
IF (cell_read_c) THEN
CALL section_vals_val_get(cell_section, "C", r_vals=cell_par)
cell%hmat(:, 3) = cell_par(:)
END IF
check = ((cell_read_a .EQV. cell_read_b) .AND. (cell_read_b .EQV. cell_read_c))
IF (.NOT. check) &
CALL cp_warn(__LOCATION__, &
"Cell Information provided through vectors A, B and C. Not all three "// &
"vectors were provided! Cell setup may be incomplete!")
! Very last option.. Trying to read cell info from ABC keyword
CALL section_vals_val_get(cell_section, "ABC", explicit=cell_read_abc)
IF (cell_read_abc) THEN
check = (cell_read_a .OR. cell_read_b .OR. cell_read_c)
IF (check) &
CALL cp_warn(__LOCATION__, &
"Cell Information provided through vectors A, B and C in conjunction with ABC."// &
" The definition of the ABC keyword will override the one provided by A,B and C.")
cell%hmat = 0.0_dp
CALL section_vals_val_get(cell_section, "ABC", r_vals=cell_par)
CALL section_vals_val_get(cell_section, "ALPHA_BETA_GAMMA", r_vals=cell_angles)
CALL set_cell_param(cell, cell_par, cell_angles, do_init_cell=.FALSE.)
END IF
! Multiple unit cell
CALL section_vals_val_get(cell_section, "MULTIPLE_UNIT_CELL", i_vals=multiple_unit_cell)
IF (ANY(multiple_unit_cell /= 1)) CALL set_multiple_unit_cell(cell, multiple_unit_cell)
CALL section_vals_val_get(cell_section, "PERIODIC", i_val=my_per)
SELECT CASE (my_per)
CASE (use_perd_x)
cell%perd = (/1, 0, 0/)
CASE (use_perd_y)
cell%perd = (/0, 1, 0/)
CASE (use_perd_z)
cell%perd = (/0, 0, 1/)
CASE (use_perd_xy)
cell%perd = (/1, 1, 0/)
CASE (use_perd_xz)
cell%perd = (/1, 0, 1/)
CASE (use_perd_yz)
cell%perd = (/0, 1, 1/)
CASE (use_perd_xyz)
cell%perd = (/1, 1, 1/)
CASE (use_perd_none)
cell%perd = (/0, 0, 0/)
CASE DEFAULT
CPABORT("")
END SELECT
! Load requested cell symmetry
CALL section_vals_val_get(cell_section, "SYMMETRY", i_val=cell%symmetry_id)
! Initialize cell
CALL init_cell(cell)
IF (.NOT. my_check) RETURN
cell_ref_section => section_vals_get_subs_vals(cell_section, &
"CELL_REF")
IF (parsed_cp2k_input(cell_ref_section, check_this_section=.TRUE.)) THEN
IF (PRESENT(use_ref_cell)) use_ref_cell = .TRUE.
CALL read_cell(cell_ref, cell_ref, use_ref_cell, cell_section=cell_ref_section, &
check_for_ref=.FALSE., para_env=para_env)
ELSE
CALL cell_clone(cell, cell_ref)
IF (PRESENT(use_ref_cell)) use_ref_cell = .FALSE.
END IF
END SUBROUTINE read_cell
! **************************************************************************************************
!> \brief utility function to ease the transition to the new input.
!> returns true if the new input was parsed
!> \param input_file the parsed input file
!> \param check_this_section ...
!> \retval res ...
!> \author fawzi
! **************************************************************************************************
FUNCTION parsed_cp2k_input(input_file, check_this_section) RESULT(res)
TYPE(section_vals_type), POINTER :: input_file
LOGICAL, INTENT(IN), OPTIONAL :: check_this_section
LOGICAL :: res
CHARACTER(len=*), PARAMETER :: routineN = 'parsed_cp2k_input', &
routineP = moduleN//':'//routineN
LOGICAL :: my_check
TYPE(section_vals_type), POINTER :: glob_section
my_check = .FALSE.
IF (PRESENT(check_this_section)) my_check = check_this_section
res = ASSOCIATED(input_file)
IF (res) THEN
CPASSERT(input_file%ref_count > 0)
IF (.NOT. my_check) THEN
glob_section => section_vals_get_subs_vals(input_file, "GLOBAL")
CALL section_vals_get(glob_section, explicit=res)
ELSE
CALL section_vals_get(input_file, explicit=res)
END IF
END IF
END FUNCTION parsed_cp2k_input
! **************************************************************************************************
!> \brief Setup of the multiple unit_cell
!> \param cell ...
!> \param multiple_unit_cell ...
!> \date 05.2009
!> \author Teodoro Laino [tlaino]
!> \version 1.0
! **************************************************************************************************
SUBROUTINE set_multiple_unit_cell(cell, multiple_unit_cell)
TYPE(cell_type), POINTER :: cell
INTEGER, DIMENSION(:), POINTER :: multiple_unit_cell
CHARACTER(len=*), PARAMETER :: routineN = 'set_multiple_unit_cell', &
routineP = moduleN//':'//routineN
! Fail is one of the value is set to zero..
IF (ANY(multiple_unit_cell <= 0)) &
CALL cp_abort(__LOCATION__, &
"CELL%MULTIPLE_UNIT_CELL accepts only integer values larger than 0! "// &
"A value of 0 or negative is meaningless!")
! scale abc accordingly user request
cell%hmat(:, 1) = cell%hmat(:, 1)*multiple_unit_cell(1)
cell%hmat(:, 2) = cell%hmat(:, 2)*multiple_unit_cell(2)
cell%hmat(:, 3) = cell%hmat(:, 3)*multiple_unit_cell(3)
END SUBROUTINE set_multiple_unit_cell
! **************************************************************************************************
!> \brief Read cell information from an external file
!> \param cell_section ...
!> \param para_env ...
!> \date 02.2008
!> \author Teodoro Laino [tlaino] - University of Zurich
!> \version 1.0
! **************************************************************************************************
SUBROUTINE read_cell_from_external_file(cell_section, para_env)
TYPE(section_vals_type), POINTER :: cell_section
TYPE(cp_para_env_type), POINTER :: para_env
CHARACTER(len=*), PARAMETER :: routineN = 'read_cell_from_external_file', &
routineP = moduleN//':'//routineN
CHARACTER(LEN=default_path_length) :: cell_file_name
INTEGER :: i, idum, j, my_format, n_rep
LOGICAL :: explicit, my_end
REAL(KIND=dp) :: xdum
REAL(KIND=dp), DIMENSION(3, 3) :: hmat
REAL(KIND=dp), DIMENSION(:), POINTER :: cell_par
TYPE(cp_parser_type), POINTER :: parser
NULLIFY (parser)
CALL section_vals_val_get(cell_section, "CELL_FILE_NAME", c_val=cell_file_name)
CALL section_vals_val_get(cell_section, "CELL_FILE_FORMAT", i_val=my_format)
CALL parser_create(parser, cell_file_name, para_env=para_env)
CALL parser_get_next_line(parser, 1)
SELECT CASE (my_format)
CASE (do_cell_cp2k)
my_end = .FALSE.
DO WHILE (.NOT. my_end)
READ (parser%input_line, *) idum, xdum, hmat(:, 1), hmat(:, 2), hmat(:, 3)
CALL parser_get_next_line(parser, 1, at_end=my_end)
END DO
CASE (do_cell_xsc)
READ (parser%input_line, *) idum, hmat(:, 1), hmat(:, 2), hmat(:, 3)
END SELECT
CALL parser_release(parser)
CALL section_vals_val_unset(cell_section, "CELL_FILE_NAME")
CALL section_vals_val_unset(cell_section, "CELL_FILE_FORMAT")
! Conver to CP2K units
DO i = 1, 3
DO j = 1, 3
hmat(j, i) = cp_unit_to_cp2k(hmat(j, i), "angstrom")
END DO
END DO
! Check if the cell was already defined
explicit = .FALSE.
CALL section_vals_val_get(cell_section, "A", n_rep_val=n_rep)
explicit = explicit .OR. (n_rep == 1)
CALL section_vals_val_get(cell_section, "B", n_rep_val=n_rep)
explicit = explicit .OR. (n_rep == 1)
CALL section_vals_val_get(cell_section, "C", n_rep_val=n_rep)
explicit = explicit .OR. (n_rep == 1)
CALL section_vals_val_get(cell_section, "ABC", n_rep_val=n_rep)
explicit = explicit .OR. (n_rep == 1)
! Possibly print a warning
IF (explicit) &
CALL cp_warn(__LOCATION__, &
"Cell specification (A,B,C or ABC) provided together with the external "// &
"cell setup! Ignoring (A,B,C or ABC) and proceeding with info read from the "// &
"external file! ")
! Copy cell information in the A, B, C fields..(we may need them later on..)
ALLOCATE (cell_par(3))
cell_par = hmat(:, 1)
CALL section_vals_val_set(cell_section, "A", r_vals_ptr=cell_par)
ALLOCATE (cell_par(3))
cell_par = hmat(:, 2)
CALL section_vals_val_set(cell_section, "B", r_vals_ptr=cell_par)
ALLOCATE (cell_par(3))
cell_par = hmat(:, 3)
CALL section_vals_val_set(cell_section, "C", r_vals_ptr=cell_par)
! Unset possible keywords
CALL section_vals_val_unset(cell_section, "ABC")
CALL section_vals_val_unset(cell_section, "ALPHA_BETA_GAMMA")
END SUBROUTINE read_cell_from_external_file
! **************************************************************************************************
!> \brief Write the cell parameters to the output unit.
!> \param cell ...
!> \param subsys_section ...
!> \param cell_ref ...
!> \param label ...
!> \date 02.06.2000
!> \par History
!> - 11.2008 Teodoro Laino [tlaino] - rewrite and enabling user driven units
!> \author Matthias Krack
!> \version 1.0
! **************************************************************************************************
RECURSIVE SUBROUTINE write_cell(cell, subsys_section, cell_ref, label)
TYPE(cell_type), POINTER :: cell
TYPE(section_vals_type), POINTER :: subsys_section
TYPE(cell_type), OPTIONAL, POINTER :: cell_ref
CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: label
CHARACTER(len=*), PARAMETER :: routineN = 'write_cell', routineP = moduleN//':'//routineN
CHARACTER(LEN=default_string_length) :: my_label, unit_str
INTEGER :: output_unit
REAL(KIND=dp) :: alpha, beta, gamma, val
REAL(KIND=dp), DIMENSION(3) :: abc
TYPE(cp_logger_type), POINTER :: logger
TYPE(enumeration_type), POINTER :: enum
TYPE(keyword_type), POINTER :: keyword
TYPE(section_type), POINTER :: section
NULLIFY (enum)
NULLIFY (keyword)
NULLIFY (logger)
NULLIFY (section)
logger => cp_get_default_logger()
my_label = "CELL|"
IF (PRESENT(label)) my_label = TRIM(label)
output_unit = cp_print_key_unit_nr(logger, subsys_section, "PRINT%CELL", &
extension=".Log")
CALL section_vals_val_get(subsys_section, "PRINT%CELL%UNIT", c_val=unit_str)
IF (output_unit > 0) THEN
CALL get_cell(cell=cell, abc=abc, alpha=alpha, beta=beta, gamma=gamma)
WRITE (UNIT=output_unit, FMT='( )')
val = cp_unit_from_cp2k(cell%deth, TRIM(unit_str)//"^3")
WRITE (UNIT=output_unit, FMT="(T2,A,T61,F20.3)") &
TRIM(my_label)//" Volume ["//TRIM(unit_str)//"^3]:", val
val = cp_unit_from_cp2k(1.0_dp, TRIM(unit_str))
WRITE (UNIT=output_unit, FMT="(T2,A,T30,3F10.3,4X,A6,F11.3)") &
TRIM(my_label)//" Vector a ["//TRIM(unit_str)//"]:", cell%hmat(:, 1)*val, &
"|a| = ", abc(1)*val, &
TRIM(my_label)//" Vector b ["//TRIM(unit_str)//"]:", cell%hmat(:, 2)*val, &
"|b| = ", abc(2)*val, &
TRIM(my_label)//" Vector c ["//TRIM(unit_str)//"]:", cell%hmat(:, 3)*val, &
"|c| = ", abc(3)*val
WRITE (UNIT=output_unit, FMT="(T2,A,T70,F11.3)") &
TRIM(my_label)//" Angle (b,c), alpha [degree]: ", alpha, &
TRIM(my_label)//" Angle (a,c), beta [degree]: ", beta, &
TRIM(my_label)//" Angle (a,b), gamma [degree]: ", gamma
IF (cell%symmetry_id /= cell_sym_none) THEN
CALL create_cell_section(section)
keyword => section_get_keyword(section, "SYMMETRY")
CALL keyword_get(keyword, enum=enum)
WRITE (UNIT=output_unit, FMT="(T2,A,T61,A20)") &
TRIM(my_label)//" Requested initial symmetry: ", &
ADJUSTR(TRIM(enum_i2c(enum, cell%symmetry_id)))
CALL section_release(section)
END IF
IF (cell%orthorhombic) THEN
WRITE (UNIT=output_unit, FMT="(T2,A,T78,A3)") &
TRIM(my_label)//" Numerically orthorhombic: ", "YES"
ELSE
WRITE (UNIT=output_unit, FMT="(T2,A,T78,A3)") &
TRIM(my_label)//" Numerically orthorhombic: ", " NO"
END IF
END IF
CALL cp_print_key_finished_output(output_unit, logger, subsys_section, &
"PRINT%CELL")
IF (PRESENT(cell_ref)) THEN
CALL write_cell(cell_ref, subsys_section, label="CELL_REF|")
END IF
END SUBROUTINE write_cell
END MODULE cell_methods
|
import BlissTheme
import ComposableArchitecture
import Dependencies
import InputOutput
import JsonPrettyClient
import SharedModels
import SwiftUI
public struct JsonPrettyReducer: ReducerProtocol {
public init() {}
public struct State: Equatable {
var inputOutput: InputOutputAttributedEditorsReducer.State
var isConversionRequestInFlight = false
public init(inputOutput: InputOutputAttributedEditorsReducer.State = .init()) {
self.inputOutput = inputOutput
}
public init(input: String, output: String = "") {
self.inputOutput = .init(input: .init(text: input), output: .init(text: .init(string: output)))
}
public var outputText: String {
inputOutput.output.text.string
}
}
public enum Action: BindableAction, Equatable {
case binding(BindingAction<State>)
case convertButtonTouched
case conversionResponse(TaskResult<NSAttributedString>)
case inputOutput(InputOutputAttributedEditorsReducer.Action)
}
@Dependency(\.jsonPretty) var jsonPretty
private enum CancelID { case conversionRequest }
public var body: some ReducerProtocol<State, Action> {
Reduce<State, Action> { state, action in
switch action {
case .binding:
return .none
case .convertButtonTouched:
state.isConversionRequestInFlight = true
return
.run { [input = state.inputOutput.input] send in
await send(
.conversionResponse(
TaskResult {
try await jsonPretty.convert(input.text)
}
)
)
}
.cancellable(id: CancelID.conversionRequest, cancelInFlight: true)
case let .conversionResponse(.success(swiftCode)):
state.isConversionRequestInFlight = false
// https://github.com/pointfreeco/swift-composable-architecture/discussions/1952#discussioncomment-5167956
return state.inputOutput.output.updateText(swiftCode)
.map { Action.inputOutput(.output($0)) }
case let .conversionResponse(.failure(error)):
state.isConversionRequestInFlight = false
let attributedString = errorAttributedString("\(error)")
return state.inputOutput.output.updateText(attributedString)
.map { Action.inputOutput(.output($0)) }
case .inputOutput:
return .none
}
}
Scope(state: \.inputOutput, action: /Action.inputOutput) {
InputOutputAttributedEditorsReducer()
}
}
}
public struct JsonPrettyView: View {
let store: StoreOf<JsonPrettyReducer>
@ObservedObject var viewStore: ViewStoreOf<JsonPrettyReducer>
public init(store: StoreOf<JsonPrettyReducer>) {
self.store = store
self.viewStore = ViewStore(store)
}
public var body: some View {
VStack {
Button(action: { viewStore.send(.convertButtonTouched) }) {
Text(NSLocalizedString("Format", bundle: Bundle.module, comment: ""))
.overlay(viewStore.isConversionRequestInFlight ? ProgressView() : nil)
}
.keyboardShortcut(.return, modifiers: [.command])
.help(NSLocalizedString("Format code (Cmd+Return)", bundle: Bundle.module, comment: ""))
InputOutputAttributedEditorsView(
store: store.scope(state: \.inputOutput, action: JsonPrettyReducer.Action.inputOutput),
inputEditorTitle: NSLocalizedString("Raw", bundle: Bundle.module, comment: ""),
outputEditorTitle: NSLocalizedString("Pretty", bundle: Bundle.module, comment: ""),
keyForFraction: SettingsKey.JsonPretty.splitViewFraction,
keyForLayout: SettingsKey.JsonPretty.splitViewLayout
)
}
}
}
// preview
struct JsonPrettyReducer_Previews: PreviewProvider {
static var previews: some View {
JsonPrettyView(store: .init(initialState: .init(), reducer: JsonPrettyReducer()))
}
}
|
using Test
using Checkpointing
using LinearAlgebra
using DataStructures
# All tested AD tools
using Zygote, Enzyme
abstract type ADtools end
struct ZygoteTool <: ADtools end
struct EnzymeTool <: ADtools end
adtools = [ZygoteTool(), EnzymeTool()]
@testset "Checkpointing.jl" begin
@testset "Enzyme..." begin
include("speelpenning.jl")
errf, errg = main()
@test isapprox(errf, 0.0; atol = 1e-15)
@test isapprox(errg, 0.0; atol = 1e-15)
end
@testset "Revolve..." begin
global steps = 50
global checkpoints = 7
global verbose = 0
include("../examples/printaction.jl")
revolve = main(steps, checkpoints)
@test revolve.numfwd == 105
@test revolve.numstore == 28
@test revolve.numinv == 177
end
@testset "Testing optcontrol..." begin
include("../examples/optcontrol.jl")
@testset "AD tool $adtool" for adtool in adtools
@testset "Revolve..." begin
steps = 100
snaps = 3
info = 0
revolve = Revolve{Model}(steps, snaps; verbose=info)
F, L, F_opt, L_opt = muoptcontrol(revolve, steps, adtool)
@test isapprox(F_opt, F, rtol=1e-4)
@test isapprox(L_opt, L, rtol=1e-4)
end
@testset "Periodic..." begin
steps = 100
snaps = 4
info = 0
periodic = Periodic{Model}(steps, snaps; verbose=info)
F, L, F_opt, L_opt = muoptcontrol(periodic, steps, adtool)
@test isapprox(F_opt, F, rtol=1e-4)
@test isapprox(L_opt, L, rtol=1e-4)
end
end
end
@testset "Testing heat example" begin
include("../examples/heat.jl")
@testset "AD tool $adtool" for adtool in adtools
@testset "Revolve..." begin
steps = 500
snaps = 4
info = 0
revolve = Revolve{Heat}(steps, snaps; verbose=info)
T, dT = heat_for(revolve, steps, adtool)
@test isapprox(norm(T), 66.21987468492061, atol=1e-11)
@test isapprox(norm(dT), 6.970279349365908, atol=1e-11)
end
@testset "Periodic..." begin
steps = 500
snaps = 4
info = 0
periodic = Periodic{Heat}(steps, snaps; verbose=info)
T, dT = heat_for(periodic, steps, adtool)
@test isapprox(norm(T), 66.21987468492061, atol=1e-11)
@test isapprox(norm(dT), 6.970279349365908, atol=1e-11)
end
@testset "Online_r2..." begin
steps = 500
snaps = 100
info = 0
online = Online_r2{Heat}(snaps; verbose=info)
T, dT = heat_while(online, steps, adtool)
@test isapprox(norm(T), 66.21987468492061, atol=1e-11)
@test isapprox(norm(dT), 6.970279349365908, atol=1e-11)
end
end
@testset "Testing HDF5 storage using heat example" begin
@testset "AD tool $adtool" for adtool in adtools
@testset "Revolve..." begin
steps = 500
snaps = 4
info = 0
revolve = Revolve{Heat}(steps, snaps; storage=HDF5Storage{Heat}(snaps), verbose=info)
T, dT = heat_for(revolve, steps, adtool)
@test isapprox(norm(T), 66.21987468492061, atol=1e-11)
@test isapprox(norm(dT), 6.970279349365908, atol=1e-11)
end
@testset "Periodic..." begin
steps = 500
snaps = 4
info = 0
periodic = Periodic{Heat}(steps, snaps; storage=HDF5Storage{Heat}(snaps), verbose=info)
T, dT = heat_for(periodic, steps, adtool)
@test isapprox(norm(T), 66.21987468492061, atol=1e-11)
@test isapprox(norm(dT), 6.970279349365908, atol=1e-11)
end
@testset "Online_r2..." begin
steps = 500
snaps = 100
info = 0
online = Online_r2{Heat}(snaps; storage=HDF5Storage{Heat}(snaps), verbose=info)
T, dT = heat_while(online, steps, adtool)
@test isapprox(norm(T), 66.21987468492061, atol=1e-11)
@test isapprox(norm(dT), 6.970279349365908, atol=1e-11)
end
end
end
end
@testset "Test box model example" begin
include("../examples/box_model.jl")
@testset "AD tool $(adtool)" for adtool in adtools
@testset "Revolve..." begin
steps = 10000
snaps = 100
info = 0
revolve = Revolve{Box}(steps, snaps; verbose=info)
T, dT = box_for(revolve, steps, adtool)
@test isapprox(T, 21.41890316892692)
@test isapprox(dT[5], 0.00616139595759519)
end
@testset "Periodic..." begin
steps = 10000
snaps = 100
info = 0
periodic = Periodic{Box}(steps, snaps; verbose=info)
T, dT = box_for(periodic, steps, adtool)
@test isapprox(T, 21.41890316892692)
@test isapprox(dT[5], 0.00616139595759519)
end
@testset "Online_r2..." begin
steps = 10000
snaps = 500
info = 0
online = Online_r2{Box}(snaps; verbose=info)
T, dT = box_while(online, steps, adtool)
@test isapprox(T, 21.41890316892692)
@test isapprox(dT[5], 0.00616139595759519)
end
end
end
@testset "Multilevel" begin
include("multilevel.jl")
end
end
|
package application
import (
"ddd-demo/domain/entity"
"ddd-demo/domain/repository"
)
type userApp struct {
us repository.UserRepository
}
//UserApp implements the UserAppInterface
var _ UserAppInterface = &userApp{}
type UserAppInterface interface {
SaveUser(*entity.User) (*entity.User, map[string]string)
GetUsers() ([]entity.User, error)
GetUser(int64) (*entity.User, error)
GetUserByEmailAndPassword(*entity.User) (*entity.User, map[string]string)
}
func (u *userApp) SaveUser(user *entity.User) (*entity.User, map[string]string) {
return u.us.SaveUser(user)
}
func (u *userApp) GetUser(userId int64) (*entity.User, error) {
return u.us.GetUser(userId)
}
func (u *userApp) GetUsers() ([]entity.User, error) {
return u.us.GetUsers()
}
func (u *userApp) GetUserByEmailAndPassword(user *entity.User) (*entity.User, map[string]string) {
return u.us.GetUserByEmailAndPassword(user)
}
|
import React, { Component } from 'react';
import {
Text,
View,
StyleSheet,
TextInput,
Button,
ScrollView,
Image,
} from 'react-native';
import { connect } from 'react-redux';
import * as actions from './../actions';
class AddPerson extends Component {
static navigationOptions = {
tabBarLabel: 'Add Person',
tabBarIcon: ({tintColor}) => (
<Image
style={styles.addButton}
source={require('./../images/add_button.png')}
/>
)
};
onAddPresss () {
const { first_name, last_name, phone, email, company, project, notes } = this.props;
this.props.createNewContact({ first_name, last_name, phone, email, company, project, notes });
this.props.navigation.navigate('PeopleList');
}
render () {
return (
<ScrollView showsVerticalScrollIndicator={false}>
<View style={styles.form}>
<Text style={styles.title}>Add a new contact</Text>
<TextInput style={styles.fieldStyles}
placeholder={'First name...'}
value={this.props.first_name}
onChangeText={(value) => this.props.formUpdate({ prop: 'first_name', value })}
/>
<TextInput style={styles.fieldStyles}
placeholder={'Last name...'}
value={this.props.last_name}
onChangeText={(value) => this.props.formUpdate({ prop: 'last_name', value })}
/>
<TextInput style={styles.fieldStyles}
placeholder={'Phone number...'}
value={this.props.phone}
onChangeText={(value) => this.props.formUpdate({ prop: 'phone', value })}
/>
<TextInput style={styles.fieldStyles}
placeholder={'Company...'}
value={this.props.company}
onChangeText={(value) => this.props.formUpdate({ prop: 'company', value })}
/>
<TextInput style={styles.fieldStyles}
placeholder={'Project...'}
value={this.props.project}
onChangeText={(value) => this.props.formUpdate({ prop: 'project', value })}
/>
<TextInput style={styles.fieldStyles}
placeholder={'Notes...'}
value={this.props.notes}
onChangeText={(value) => this.props.formUpdate({ prop: 'notes', value })}
/>
<View style={styles.add}>
<Button title={'ADD'} onPress={this.onAddPresss.bind(this)} />
</View>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
form: {
paddingTop: 50,
paddingBottom: 10,
paddingLeft: 20,
paddingRight: 20,
justifyContent: 'space-between',
},
fieldStyles: {
height: 40,
color: 'orange',
},
addButton: {
marginBottom: 15,
},
title: {
fontSize: 20,
fontWeight: 'bold',
paddingTop: 10,
paddingBottom: 10,
},
add: {
marginTop: 30,
},
});
const mapStateToProps = (state) => {
const { first_name, last_name, phone, email, company, project, notes } = state;
return { first_name, last_name, phone, email, company, project, notes };
};
export default connect(mapStateToProps, actions)(AddPerson);
|
/*
* Copyright 2017 The Mifos Initiative.
*
* 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.
*/
package io.mifos.portfolio;
import com.google.gson.Gson;
import io.mifos.individuallending.api.v1.domain.caseinstance.CaseParameters;
import io.mifos.individuallending.api.v1.domain.caseinstance.CreditWorthinessFactor;
import io.mifos.individuallending.api.v1.domain.caseinstance.CreditWorthinessSnapshot;
import io.mifos.individuallending.api.v1.domain.product.ProductParameters;
import io.mifos.portfolio.api.v1.domain.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Consumer;
import static io.mifos.individuallending.api.v1.domain.product.AccountDesignators.*;
import static io.mifos.portfolio.AccountingFixture.*;
import static java.math.BigDecimal.ROUND_HALF_EVEN;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Fixture {
static final int MINOR_CURRENCY_UNIT_DIGITS = 2;
static final BigDecimal INTEREST_RATE = BigDecimal.valueOf(0.10).setScale(4, RoundingMode.HALF_EVEN);
static final BigDecimal ACCRUAL_PERIODS = BigDecimal.valueOf(365.2425);
private static int uniquenessSuffix = 0;
static public Product getTestProduct() {
final Product product = new Product();
product.setPatternPackage("io.mifos.individuallending.api.v1");
product.setIdentifier(generateUniqueIdentifer("agro"));
product.setName("Agricultural Loan");
product.setDescription("Loan for seeds or agricultural equipment");
product.setTermRange(new TermRange(ChronoUnit.MONTHS, 12));
product.setBalanceRange(new BalanceRange(fixScale(BigDecimal.ZERO), fixScale(new BigDecimal(10000))));
product.setInterestBasis(InterestBasis.CURRENT_BALANCE);
product.setCurrencyCode("XXX");
product.setMinorCurrencyUnitDigits(MINOR_CURRENCY_UNIT_DIGITS);
final Set<AccountAssignment> accountAssignments = new HashSet<>();
final AccountAssignment pendingDisbursalAccountAssignment = new AccountAssignment();
pendingDisbursalAccountAssignment.setDesignator(PENDING_DISBURSAL);
pendingDisbursalAccountAssignment.setLedgerIdentifier(PENDING_DISBURSAL_LEDGER_IDENTIFIER);
accountAssignments.add(pendingDisbursalAccountAssignment);
accountAssignments.add(new AccountAssignment(PROCESSING_FEE_INCOME, PROCESSING_FEE_INCOME_ACCOUNT_IDENTIFIER));
accountAssignments.add(new AccountAssignment(ORIGINATION_FEE_INCOME, LOAN_ORIGINATION_FEES_ACCOUNT_IDENTIFIER));
accountAssignments.add(new AccountAssignment(DISBURSEMENT_FEE_INCOME, DISBURSEMENT_FEE_INCOME_ACCOUNT_IDENTIFIER));
accountAssignments.add(new AccountAssignment(INTEREST_INCOME, CONSUMER_LOAN_INTEREST_ACCOUNT_IDENTIFIER));
accountAssignments.add(new AccountAssignment(INTEREST_ACCRUAL, LOAN_INTEREST_ACCRUAL_ACCOUNT_IDENTIFIER));
accountAssignments.add(new AccountAssignment(LOANS_PAYABLE, LOANS_PAYABLE_ACCOUNT_IDENTIFIER));
accountAssignments.add(new AccountAssignment(LATE_FEE_INCOME, LATE_FEE_INCOME_ACCOUNT_IDENTIFIER));
accountAssignments.add(new AccountAssignment(LATE_FEE_ACCRUAL, LATE_FEE_ACCRUAL_ACCOUNT_IDENTIFIER));
accountAssignments.add(new AccountAssignment(ARREARS_ALLOWANCE, ARREARS_ALLOWANCE_ACCOUNT_IDENTIFIER));
//accountAssignments.add(new AccountAssignment(ENTRY, ...));
// Don't assign entry account in test since it usually will not be assigned IRL.
accountAssignments.add(new AccountAssignment(LOAN_FUNDS_SOURCE, LOAN_FUNDS_SOURCE_ACCOUNT_IDENTIFIER));
final AccountAssignment customerLoanAccountAssignment = new AccountAssignment();
customerLoanAccountAssignment.setDesignator(CUSTOMER_LOAN);
customerLoanAccountAssignment.setLedgerIdentifier(CUSTOMER_LOAN_LEDGER_IDENTIFIER);
accountAssignments.add(customerLoanAccountAssignment);
product.setAccountAssignments(accountAssignments);
final ProductParameters productParameters = new ProductParameters();
productParameters.setMoratoriums(Collections.emptyList());
productParameters.setMaximumDispersalCount(5);
final Gson gson = new Gson();
product.setParameters(gson.toJson(productParameters));
return product;
}
static public Product createAdjustedProduct(final Consumer<Product> adjustment) {
final Product product = Fixture.getTestProduct();
adjustment.accept(product);
return product;
}
static public String generateUniqueIdentifer(final String prefix) {
//prefix followed by a random positive number with less than 4 digits.
return prefix + (uniquenessSuffix++);
}
static public BigDecimal fixScale(final BigDecimal bigDecimal)
{
return bigDecimal.setScale(MINOR_CURRENCY_UNIT_DIGITS, ROUND_HALF_EVEN);
}
static public Case getTestCase(final String productIdentifier) {
final Case ret = new Case();
ret.setIdentifier(generateUniqueIdentifer("loan"));
ret.setProductIdentifier(productIdentifier);
final Set<AccountAssignment> accountAssignments = new HashSet<>();
ret.setAccountAssignments(accountAssignments);
ret.setCurrentState(Case.State.CREATED.name());
final CaseParameters caseParameters = getTestCaseParameters();
final Gson gson = new Gson();
ret.setParameters(gson.toJson(caseParameters));
return ret;
}
static public Case createAdjustedCase(final String productIdentifier, final Consumer<Case> adjustment) {
final Case ret = Fixture.getTestCase(productIdentifier);
adjustment.accept(ret);
return ret;
}
static public CaseParameters getTestCaseParameters()
{
final CaseParameters ret = new CaseParameters(generateUniqueIdentifer("fred"));
ret.setCustomerIdentifier("alice");
ret.setMaximumBalance(fixScale(BigDecimal.valueOf(2000L)));
ret.setTermRange(new TermRange(ChronoUnit.MONTHS, 18));
ret.setPaymentCycle(new PaymentCycle(ChronoUnit.MONTHS, 1, 1, null, null));
final CreditWorthinessSnapshot customerCreditWorthinessSnapshot = new CreditWorthinessSnapshot();
customerCreditWorthinessSnapshot.setForCustomer("alice");
customerCreditWorthinessSnapshot.setDebts(Collections.singletonList(new CreditWorthinessFactor("some debt", fixScale(BigDecimal.valueOf(300)))));
customerCreditWorthinessSnapshot.setAssets(Collections.singletonList(new CreditWorthinessFactor("some asset", fixScale(BigDecimal.valueOf(500)))));
customerCreditWorthinessSnapshot.setIncomeSources(Collections.singletonList(new CreditWorthinessFactor("some income source", fixScale(BigDecimal.valueOf(300)))));
final CreditWorthinessSnapshot cosignerCreditWorthinessSnapshot = new CreditWorthinessSnapshot();
cosignerCreditWorthinessSnapshot.setForCustomer("seema");
cosignerCreditWorthinessSnapshot.setDebts(Collections.emptyList());
cosignerCreditWorthinessSnapshot.setAssets(Collections.singletonList(new CreditWorthinessFactor("a house", fixScale(BigDecimal.valueOf(50000)))));
cosignerCreditWorthinessSnapshot.setIncomeSources(Collections.singletonList(new CreditWorthinessFactor("retirement", fixScale(BigDecimal.valueOf(200)))));
final List<CreditWorthinessSnapshot> creditWorthinessSnapshots = new ArrayList<>();
creditWorthinessSnapshots.add(customerCreditWorthinessSnapshot);
creditWorthinessSnapshots.add(cosignerCreditWorthinessSnapshot);
ret.setCreditWorthinessSnapshots(creditWorthinessSnapshots);
return ret;
}
static public CaseParameters createAdjustedCaseParameters(final Consumer<CaseParameters> adjustment) {
final CaseParameters ret = Fixture.getTestCaseParameters();
adjustment.accept(ret);
return ret;
}
}
|
use std::{collections::HashMap, iter::Peekable, str::Chars};
use crate::token::Token;
macro_rules! try_pop_next {
($s: ident, $x:expr) => {
if $x {
$s.pop();
true
} else {
false
}
};
}
#[derive(Debug, Clone, PartialEq)]
pub struct ScannerItem {
pub token: Token,
pub line_count: usize,
pub column_count: usize,
}
#[derive(Debug, Clone)]
pub struct Scanner<'a> {
// TODO: Optimize for memory (Allow for &str and &Token)
identifiers: HashMap<String, Token>,
string_constants: HashMap<String, Token>,
input: Peekable<Chars<'a>>,
line_count: usize,
column_count: usize,
eof: bool,
}
impl<'a> Scanner<'a> {
pub fn new(input: &'a str) -> Self {
let identifiers = HashMap::from([
// Declaration Prefixes
("program".to_string(), Token::KwProgram),
("procedure".to_string(), Token::KwProcedure),
("variable".to_string(), Token::KwVariable),
// Scope Modifiers
("global".to_string(), Token::KwGlobal),
// Block Markers
("begin".to_string(), Token::KwBegin),
("end".to_string(), Token::KwEnd),
// Type Names
("integer".to_string(), Token::KwInteger),
("float".to_string(), Token::KwFloat),
("string".to_string(), Token::KwString),
("bool".to_string(), Token::KwBool),
("true".to_string(), Token::KwTrue),
("false".to_string(), Token::KwFalse),
// Control Flow
("if".to_string(), Token::KwIf),
("then".to_string(), Token::KwThen),
("else".to_string(), Token::KwElse),
("for".to_string(), Token::KwFor),
("return".to_string(), Token::KwReturn),
// Miscellaneous Keywords
("is".to_string(), Token::KwIs),
("not".to_string(), Token::KwNot),
]);
Self {
identifiers,
string_constants: HashMap::new(),
input: input.chars().peekable(),
line_count: 1,
column_count: 0,
eof: false,
}
}
fn pop(&mut self) -> Option<char> {
self.column_count += 1;
self.input.next()
}
fn pop_next_valid(&mut self) -> Option<char> {
let mut c = self.pop()?;
let mut is_comment = false;
let mut multiline_comment_count = 0;
while match c {
// Always ignore newline whitespace and reset is_comment
'\n' => {
is_comment = false;
self.line_count += 1;
self.column_count = 0;
true
}
'\r' if try_pop_next!(self, self.input.peek() == Some(&'\n')) => {
is_comment = false;
self.line_count += 1;
self.column_count = 0;
true
}
// Start comment
'/' if self.input.peek() == Some(&'/') && multiline_comment_count == 0 => {
is_comment = true;
true
}
// Start multiline comment
'/' if self.input.peek() == Some(&'*') => {
multiline_comment_count += 1;
true
}
// End multiline comment
'*' if try_pop_next!(
self,
multiline_comment_count > 0 && self.input.peek() == Some(&'/')
) =>
{
multiline_comment_count -= 1;
true
}
// Ignore anything if we are inside a comment or if it is whitespace
_ if is_comment || multiline_comment_count > 0 || c.is_whitespace() => true,
// Nothing else to ignore
_ => false,
} {
c = self.pop()?;
}
Some(c)
}
}
impl Iterator for Scanner<'_> {
type Item = ScannerItem;
fn next(&mut self) -> Option<Self::Item> {
let c = self.pop_next_valid();
let mut line_count = self.line_count;
let mut column_count = self.column_count;
if c.is_none() && !self.eof {
self.eof = true;
return Some(ScannerItem {
token: Token::EOF,
line_count,
column_count,
});
}
let c = c?;
let next_is_eq = self.input.peek() == Some(&'=');
let token = match c {
// Structure Symbols
'(' => Token::LeftParenthesis,
')' => Token::RightParenthesis,
'[' => Token::LeftBracket,
']' => Token::RightBracket,
',' => Token::Comma,
';' => Token::SemiColon,
'.' => Token::Period,
// Math Symbols
'&' => Token::BitAnd,
'|' => Token::BitOr,
'+' => Token::Plus,
'-' => Token::Minus,
'*' => Token::Multiply,
'/' => Token::Divide,
// Comparison Operators
'<' if try_pop_next!(self, next_is_eq) => Token::LessThanEqual,
'<' => Token::LessThan,
'>' if try_pop_next!(self, next_is_eq) => Token::GreaterThanEqual,
'>' => Token::GreaterThan,
'=' if try_pop_next!(self, next_is_eq) => Token::Equal,
'!' if try_pop_next!(self, next_is_eq) => Token::NotEqual,
// Assignment Operator
':' if try_pop_next!(self, next_is_eq) => Token::AssignmentOperator,
// Colon
':' => Token::Colon,
// Numbers
'0'..='9' => {
let mut num: String = c.to_string();
// Match against beginning part of the number
while matches!(self.input.peek(), Some('0'..='9')) {
num.push(self.pop().unwrap())
}
// Catch Floats
if self.input.peek() == Some(&'.') {
num.push(self.pop().unwrap());
// Match against the rest of the number
while matches!(self.input.peek(), Some('0'..='9')) {
num.push(self.pop().unwrap())
}
Token::Float(num.parse().unwrap())
} else {
Token::Integer(num.parse().unwrap())
}
}
// Strings
'"' => {
let mut s = String::new();
while !matches!(self.input.peek(), Some('"') | None) {
s.push(self.pop().unwrap())
}
// This is either a Quote or the end of the file...
// Either way, we can pop it
self.pop();
self.string_constants
.entry(s.clone())
.or_insert(Token::String(s))
.clone()
}
// Identifiers and Keywords
'a'..='z' | 'A'..='Z' => {
let mut identifier = c.to_string();
while matches!(
self.input.peek(),
Some('_') | Some('a'..='z') | Some('A'..='Z') | Some('0'..='9')
) {
identifier.push(self.pop().unwrap());
}
identifier = identifier.to_lowercase();
self.identifiers
.entry(identifier.clone())
.or_insert(Token::Identifier(identifier))
.clone()
}
// Illegal Characters
_ => {
let next = self.next()?;
line_count = next.line_count;
column_count = next.column_count;
next.token
}
};
Some(ScannerItem {
token,
line_count,
column_count,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::*;
#[rstest]
#[case("program", Token::KwProgram)]
#[case("procedure", Token::KwProcedure)]
#[case("variable", Token::KwVariable)]
#[case("global", Token::KwGlobal)]
#[case("begin", Token::KwBegin)]
#[case("end", Token::KwEnd)]
#[case("integer", Token::KwInteger)]
#[case("float", Token::KwFloat)]
#[case("string", Token::KwString)]
#[case("bool", Token::KwBool)]
#[case("true", Token::KwTrue)]
#[case("false", Token::KwFalse)]
#[case("if", Token::KwIf)]
#[case("If", Token::KwIf)]
#[case("iF", Token::KwIf)]
#[case("then", Token::KwThen)]
#[case("else", Token::KwElse)]
#[case("for", Token::KwFor)]
#[case("return", Token::KwReturn)]
#[case("is", Token::KwIs)]
#[case("not", Token::KwNot)]
#[case("(", Token::LeftParenthesis)]
#[case(")", Token::RightParenthesis)]
#[case("[", Token::LeftBracket)]
#[case("]", Token::RightBracket)]
#[case(",", Token::Comma)]
#[case(":", Token::Colon)]
#[case(";", Token::SemiColon)]
#[case(".", Token::Period)]
#[case("&", Token::BitAnd)]
#[case("|", Token::BitOr)]
#[case("+", Token::Plus)]
#[case("-", Token::Minus)]
#[case("*", Token::Multiply)]
#[case("/", Token::Divide)]
#[case("<", Token::LessThan)]
#[case("<=", Token::LessThanEqual)]
#[case(">", Token::GreaterThan)]
#[case(">=", Token::GreaterThanEqual)]
#[case("==", Token::Equal)]
#[case("!=", Token::NotEqual)]
#[case("hello", Token::Identifier("hello".to_string()))]
#[case("hElLO", Token::Identifier("hello".to_string()))]
#[case("\"hello\"", Token::String("hello".to_string()))]
#[case("8675309", Token::Integer(8675309))]
#[case("1.23", Token::Float(1.23))]
#[case(":=", Token::AssignmentOperator)]
fn correct_tokens(#[case] input: String, #[case] token: Token) {
let scanner = Scanner::new(&input);
let item = ScannerItem {
token,
line_count: 1,
column_count: 1,
};
let eof = ScannerItem {
token: Token::EOF,
line_count: 1,
column_count: input.len() + 1,
};
assert_eq!(scanner.collect::<Vec<_>>(), vec![item, eof]);
}
#[rstest]
#[case("\n >", Token::GreaterThan, 2, 3)]
#[case("\t>", Token::GreaterThan, 1, 2)]
#[case("// Single Line Comment\n>", Token::GreaterThan, 2, 1)]
#[case("/* Multi\nLine\nComment\n*/\n>", Token::GreaterThan, 5, 1)]
#[case("/* Multi\r\nLine\r\nComment\r\n*/\r\n>", Token::GreaterThan, 5, 1)]
#[case("/* BC with // double slashes */>", Token::GreaterThan, 1, 32)]
#[case("/* /* BC inside of BC */ */>", Token::GreaterThan, 1, 28)]
fn ignorables(
#[case] input: String,
#[case] token: Token,
#[case] line_count: usize,
#[case] column_count: usize,
) {
let scanner = Scanner::new(&input);
let item = ScannerItem {
token,
line_count,
column_count,
};
let eof = ScannerItem {
token: Token::EOF,
line_count,
column_count: column_count + 1,
};
assert_eq!(scanner.collect::<Vec<_>>(), vec![item, eof]);
}
}
|
package org.broadinstitute.ddp;
import static com.google.common.net.HttpHeaders.X_FORWARDED_FOR;
import static spark.Spark.afterAfter;
import static spark.Spark.awaitInitialization;
import static spark.Spark.before;
import static spark.Spark.delete;
import static spark.Spark.internalServerError;
import static spark.Spark.notFound;
import static spark.Spark.options;
import static spark.Spark.port;
import static spark.Spark.stop;
import static spark.Spark.threadPool;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.http.entity.ContentType;
import org.broadinstitute.ddp.constants.ConfigFile;
import org.broadinstitute.ddp.constants.ErrorCodes;
import org.broadinstitute.ddp.constants.RouteConstants.API;
import org.broadinstitute.ddp.content.I18nContentRenderer;
import org.broadinstitute.ddp.db.ActivityInstanceDao;
import org.broadinstitute.ddp.db.AnswerDao;
import org.broadinstitute.ddp.db.CancerStore;
import org.broadinstitute.ddp.db.ConsentElectionDao;
import org.broadinstitute.ddp.db.DBUtils;
import org.broadinstitute.ddp.db.FormInstanceDao;
import org.broadinstitute.ddp.db.SectionBlockDao;
import org.broadinstitute.ddp.db.StudyActivityDao;
import org.broadinstitute.ddp.db.StudyAdminDao;
import org.broadinstitute.ddp.db.TransactionWrapper;
import org.broadinstitute.ddp.db.UserDao;
import org.broadinstitute.ddp.db.UserDaoFactory;
import org.broadinstitute.ddp.filter.AddDDPAuthLoggingFilter;
import org.broadinstitute.ddp.filter.DsmAuthFilter;
import org.broadinstitute.ddp.filter.ExcludePathFilterWrapper;
import org.broadinstitute.ddp.filter.HttpHeaderMDCFilter;
import org.broadinstitute.ddp.filter.MDCAttributeRemovalFilter;
import org.broadinstitute.ddp.filter.MDCLogBreadCrumbFilter;
import org.broadinstitute.ddp.filter.TokenConverterFilter;
import org.broadinstitute.ddp.filter.UserAuthCheckFilter;
import org.broadinstitute.ddp.json.errors.ApiError;
import org.broadinstitute.ddp.model.dsm.DrugStore;
import org.broadinstitute.ddp.monitoring.PointsReducerFactory;
import org.broadinstitute.ddp.monitoring.StackdriverCustomMetric;
import org.broadinstitute.ddp.monitoring.StackdriverMetricsTracker;
import org.broadinstitute.ddp.pex.PexInterpreter;
import org.broadinstitute.ddp.pex.TreeWalkInterpreter;
import org.broadinstitute.ddp.route.AddProfileRoute;
import org.broadinstitute.ddp.route.CheckIrbPasswordRoute;
import org.broadinstitute.ddp.route.CreateActivityInstanceRoute;
import org.broadinstitute.ddp.route.CreateMailAddressRoute;
import org.broadinstitute.ddp.route.CreateTemporaryUserRoute;
import org.broadinstitute.ddp.route.DeleteMailAddressRoute;
import org.broadinstitute.ddp.route.DeleteMedicalProviderRoute;
import org.broadinstitute.ddp.route.DeleteTempMailingAddressRoute;
import org.broadinstitute.ddp.route.DsmExitUserRoute;
import org.broadinstitute.ddp.route.DsmTriggerOnDemandActivityRoute;
import org.broadinstitute.ddp.route.ErrorRoute;
import org.broadinstitute.ddp.route.ExportStudyRoute;
import org.broadinstitute.ddp.route.GetActivityInstanceRoute;
import org.broadinstitute.ddp.route.GetActivityInstanceStatusTypeListRoute;
import org.broadinstitute.ddp.route.GetAdminStudiesRoute;
import org.broadinstitute.ddp.route.GetConsentSummariesRoute;
import org.broadinstitute.ddp.route.GetConsentSummaryRoute;
import org.broadinstitute.ddp.route.GetCountryAddressInfoRoute;
import org.broadinstitute.ddp.route.GetCountryAddressInfoSummariesRoute;
import org.broadinstitute.ddp.route.GetDeployedAppVersionRoute;
import org.broadinstitute.ddp.route.GetDsmConsentPdfRoute;
import org.broadinstitute.ddp.route.GetDsmDrugSuggestionsRoute;
import org.broadinstitute.ddp.route.GetDsmInstitutionRequestsRoute;
import org.broadinstitute.ddp.route.GetDsmKitRequestsRoute;
import org.broadinstitute.ddp.route.GetDsmMedicalRecordRoute;
import org.broadinstitute.ddp.route.GetDsmOnDemandActivitiesRoute;
import org.broadinstitute.ddp.route.GetDsmParticipantInstitutionsRoute;
import org.broadinstitute.ddp.route.GetDsmParticipantStatusRoute;
import org.broadinstitute.ddp.route.GetDsmReleasePdfRoute;
import org.broadinstitute.ddp.route.GetDsmStudyParticipant;
import org.broadinstitute.ddp.route.GetDsmTriggeredInstancesRoute;
import org.broadinstitute.ddp.route.GetGovernedStudyParticipantsRoute;
import org.broadinstitute.ddp.route.GetInstitutionSuggestionsRoute;
import org.broadinstitute.ddp.route.GetMailAddressRoute;
import org.broadinstitute.ddp.route.GetMailingListRoute;
import org.broadinstitute.ddp.route.GetMedicalProviderListRoute;
import org.broadinstitute.ddp.route.GetParticipantDefaultMailAddressRoute;
import org.broadinstitute.ddp.route.GetParticipantInfoRoute;
import org.broadinstitute.ddp.route.GetParticipantMailAddressRoute;
import org.broadinstitute.ddp.route.GetPrequalifierInstanceRoute;
import org.broadinstitute.ddp.route.GetProfileRoute;
import org.broadinstitute.ddp.route.GetStudiesRoute;
import org.broadinstitute.ddp.route.GetStudyDetailRoute;
import org.broadinstitute.ddp.route.GetStudyPasswordRequirementsRoute;
import org.broadinstitute.ddp.route.GetTempMailingAddressRoute;
import org.broadinstitute.ddp.route.GetUserAnnouncementsRoute;
import org.broadinstitute.ddp.route.GetWorkflowRoute;
import org.broadinstitute.ddp.route.GetWorkspacesRoute;
import org.broadinstitute.ddp.route.HealthCheckRoute;
import org.broadinstitute.ddp.route.JoinMailingListRoute;
import org.broadinstitute.ddp.route.ListCancersRoute;
import org.broadinstitute.ddp.route.PatchFormAnswersRoute;
import org.broadinstitute.ddp.route.PatchMedicalProviderRoute;
import org.broadinstitute.ddp.route.PatchProfileRoute;
import org.broadinstitute.ddp.route.PostMedicalProviderRoute;
import org.broadinstitute.ddp.route.PostPasswordResetRoute;
import org.broadinstitute.ddp.route.PutFormAnswersRoute;
import org.broadinstitute.ddp.route.PutTempMailingAddressRoute;
import org.broadinstitute.ddp.route.SendDsmNotificationRoute;
import org.broadinstitute.ddp.route.SendEmailRoute;
import org.broadinstitute.ddp.route.SendExitNotificationRoute;
import org.broadinstitute.ddp.route.SetParticipantDefaultMailAddressRoute;
import org.broadinstitute.ddp.route.UpdateMailAddressRoute;
import org.broadinstitute.ddp.route.UpdateUserEmailRoute;
import org.broadinstitute.ddp.route.UpdateUserPasswordRoute;
import org.broadinstitute.ddp.route.UserActivityInstanceListRoute;
import org.broadinstitute.ddp.route.UserRegistrationRoute;
import org.broadinstitute.ddp.route.VerifyMailAddressRoute;
import org.broadinstitute.ddp.schedule.DsmCancerLoaderJob;
import org.broadinstitute.ddp.schedule.DsmDrugLoaderJob;
import org.broadinstitute.ddp.schedule.JobScheduler;
import org.broadinstitute.ddp.security.JWTConverter;
import org.broadinstitute.ddp.service.ActivityInstanceService;
import org.broadinstitute.ddp.service.AddressService;
import org.broadinstitute.ddp.service.CancerService;
import org.broadinstitute.ddp.service.ConsentService;
import org.broadinstitute.ddp.service.DsmCancerListService;
import org.broadinstitute.ddp.service.DsmParticipantStatusService;
import org.broadinstitute.ddp.service.FireCloudExportService;
import org.broadinstitute.ddp.service.FormActivityService;
import org.broadinstitute.ddp.service.MedicalRecordService;
import org.broadinstitute.ddp.service.PdfBucketService;
import org.broadinstitute.ddp.service.PdfGenerationService;
import org.broadinstitute.ddp.service.PdfService;
import org.broadinstitute.ddp.service.WorkflowService;
import org.broadinstitute.ddp.transformers.SimpleJsonTransformer;
import org.broadinstitute.ddp.util.ConfigManager;
import org.broadinstitute.ddp.util.DsmDrugLoader;
import org.broadinstitute.ddp.util.LiquibaseUtil;
import org.broadinstitute.ddp.util.LogbackConfigurationPrinter;
import org.broadinstitute.ddp.util.RouteUtil;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import spark.Filter;
import spark.Request;
import spark.Response;
import spark.ResponseTransformer;
import spark.Route;
import spark.Spark;
import spark.route.HttpMethod;
public class DataDonationPlatform {
public static final String MDC_STUDY = "Study";
public static final String MDC_ROUTE_CLASS = "RouteClass";
private static final Logger LOG = LoggerFactory.getLogger(DataDonationPlatform.class);
private static final String[] CORS_HTTP_METHODS = new String[] {"GET", "PUT", "POST", "OPTIONS", "PATCH"};
private static final String[] CORS_HTTP_HEADERS = new String[] {"Content-Type", "Authorization", "X-Requested-With",
"Content-Length", "Accept", "Origin", ""};
private static final Map<String, String> pathToClass = new HashMap<>();
private static Scheduler scheduler = null;
/**
* Stop the server using the default wait time.
*/
public static void shutdown() {
shutdown(1000);
}
/**
* Stop the Spark server and give it time to close.
*
* @param millisecs milliseconds to wait for Spark to close
*/
public static void shutdown(int millisecs) {
if (scheduler != null) {
JobScheduler.shutdownScheduler(scheduler, false);
}
stop();
try {
LOG.info("Pausing for {}ms for server to stop", millisecs);
Thread.sleep(millisecs);
} catch (InterruptedException e) {
LOG.warn("Wait interrupted", e);
}
LOG.info("ddp shutdown complete");
}
public static void main(String[] args) {
try {
start();
} catch (Exception e) {
LOG.error("Could not start ddp", e);
shutdown();
}
}
private static void start() {
LogbackConfigurationPrinter.printLoggingConfiguration();
Config cfg = ConfigManager.getInstance().getConfig();
boolean doLiquibase = cfg.getBoolean(ConfigFile.DO_LIQUIBASE);
int maxConnections = cfg.getInt(ConfigFile.NUM_POOLED_CONNECTIONS);
String firecloudKeysLocation = System.getProperty(ConfigFile.FIRECLOUD_KEYS_DIR_ENV_VAR);
if (firecloudKeysLocation == null) {
LOG.error("System property {} was not set. Exiting program", ConfigFile.FIRECLOUD_KEYS_DIR_ENV_VAR);
System.exit(-1);
}
File firecloudKeysDir = new File(firecloudKeysLocation);
if (!firecloudKeysDir.exists() || !firecloudKeysDir.isDirectory()) {
LOG.error("Cannot find directory {} specified in system property {}. Exiting program", firecloudKeysDir,
ConfigFile.FIRECLOUD_KEYS_DIR_ENV_VAR);
System.exit(-1);
}
int requestThreadTimeout = cfg.getInt(ConfigFile.THREAD_TIMEOUT);
String healthcheckPassword = cfg.getString(ConfigFile.HEALTHCHECK_PASSWORD);
int port = cfg.getInt(ConfigFile.PORT);
port(port);
String dbUrl = cfg.getString(ConfigFile.DB_URL);
LOG.info("Using db {}", dbUrl);
TransactionWrapper.init(
new TransactionWrapper.DbConfiguration(TransactionWrapper.DB.APIS, maxConnections, dbUrl));
threadPool(-1, -1, requestThreadTimeout);
Config sqlConfig = ConfigFactory.load(ConfigFile.SQL_CONFIG_FILE);
initSqlCommands(sqlConfig);
if (doLiquibase) {
LOG.info("Running liquibase migrations against " + dbUrl);
LiquibaseUtil.runLiquibase(dbUrl, TransactionWrapper.DB.APIS);
}
UserDao userDao = UserDaoFactory.createFromSqlConfig(sqlConfig);
final AnswerDao answerDao = AnswerDao.fromSqlConfig(sqlConfig);
SectionBlockDao sectionBlockDao = new SectionBlockDao(new I18nContentRenderer());
FormInstanceDao formInstanceDao = FormInstanceDao.fromDaoAndConfig(sectionBlockDao, sqlConfig);
ActivityInstanceDao activityInstanceDao = new ActivityInstanceDao(formInstanceDao);
PexInterpreter interpreter = new TreeWalkInterpreter();
final ActivityInstanceService actInstService = new ActivityInstanceService(activityInstanceDao, interpreter);
final FireCloudExportService fireCloudExportService = FireCloudExportService.fromSqlConfig(sqlConfig);
final StudyAdminDao studyAdminDao = StudyAdminDao.init(sqlConfig, firecloudKeysDir);
SimpleJsonTransformer responseSerializer = new SimpleJsonTransformer();
before("*", new HttpHeaderMDCFilter(X_FORWARDED_FOR));
before("*", new MDCLogBreadCrumbFilter());
before("*", new Filter() {
@Override
public void handle(Request request, Response response) throws Exception {
MDC.put(MDC_STUDY, RouteUtil.parseStudyGuid(request.pathInfo()));
}
});
enableCORS("*", String.join(",", CORS_HTTP_METHODS), String.join(",", CORS_HTTP_HEADERS));
setupCatchAllErrorHandling();
// before filter converts jwt into DDP_AUTH request attribute
// we exclude the DSM paths. DSM paths have own separate authentication
beforeWithExclusion(API.BASE + "/*", new String[] {API.DSM_BASE + "/*", API.CHECK_IRB_PASSWORD},
new TokenConverterFilter(new JWTConverter(userDao)));
beforeWithExclusion(API.BASE + "/*", new String[] {API.DSM_BASE + "/*", API.CHECK_IRB_PASSWORD}, new AddDDPAuthLoggingFilter());
// Internal routes
get(API.HEALTH_CHECK, new HealthCheckRoute(healthcheckPassword), responseSerializer);
get(API.DEPLOYED_VERSION, new GetDeployedAppVersionRoute(), responseSerializer);
get(API.INTERNAL_ERROR, new ErrorRoute(), responseSerializer);
post(API.REGISTRATION, new UserRegistrationRoute(interpreter), responseSerializer);
post(API.TEMP_USERS, new CreateTemporaryUserRoute(userDao), responseSerializer);
// List available studies & get detailed information on a particular study
get(API.STUDY_ALL, new GetStudiesRoute(), responseSerializer);
get(API.STUDY_DETAIL, new GetStudyDetailRoute(), responseSerializer);
get(API.ADDRESS_COUNTRIES, new GetCountryAddressInfoSummariesRoute(), responseSerializer);
get(API.ADDRESS_COUNTRY_DETAILS, new GetCountryAddressInfoRoute(), responseSerializer);
// User route filter
before(API.USER_ALL, new UserAuthCheckFilter()
.addTempUserWhitelist(HttpMethod.get, API.USER_PROFILE)
.addTempUserWhitelist(HttpMethod.get, API.USER_STUDY_WORKFLOW)
.addTempUserWhitelist(HttpMethod.get, API.USER_ACTIVITIES_INSTANCE)
.addTempUserWhitelist(HttpMethod.patch, API.USER_ACTIVITY_ANSWERS)
.addTempUserWhitelist(HttpMethod.put, API.USER_ACTIVITY_ANSWERS)
);
// Governed participant routes
get(API.USER_STUDY_PARTICIPANTS, new GetGovernedStudyParticipantsRoute(), responseSerializer);
// User profile routes
get(API.USER_PROFILE, new GetProfileRoute(userDao), responseSerializer);
post(API.USER_PROFILE, new AddProfileRoute(userDao), responseSerializer);
patch(API.USER_PROFILE, new PatchProfileRoute(userDao), responseSerializer);
// User mailing address routes
AddressService addressService = new AddressService(cfg.getString(ConfigFile.EASY_POST_API_KEY),
cfg.getString(ConfigFile.GEOCODING_API_KEY));
post(API.PARTICIPANT_ADDRESS, new CreateMailAddressRoute(addressService), responseSerializer);
get(API.PARTICIPANT_ADDRESS, new GetParticipantMailAddressRoute(addressService), responseSerializer);
post(API.DEFAULT_PARTICIPANT_ADDRESS,
new SetParticipantDefaultMailAddressRoute(addressService), responseSerializer);
get(API.DEFAULT_PARTICIPANT_ADDRESS,
new GetParticipantDefaultMailAddressRoute(addressService), responseSerializer);
get(API.ADDRESS, new GetMailAddressRoute(addressService), responseSerializer);
put(API.ADDRESS, new UpdateMailAddressRoute(addressService), responseSerializer);
delete(API.ADDRESS, new DeleteMailAddressRoute(addressService));
get(API.PARTICIPANT_TEMP_ADDRESS, new GetTempMailingAddressRoute(), responseSerializer);
put(API.PARTICIPANT_TEMP_ADDRESS, new PutTempMailingAddressRoute());
delete(API.PARTICIPANT_TEMP_ADDRESS, new DeleteTempMailingAddressRoute());
post(API.ADDRESS_VERIFY, new VerifyMailAddressRoute(addressService), responseSerializer);
get(API.PARTICIPANTS_INFO_FOR_STUDY, new GetParticipantInfoRoute(), responseSerializer);
// Workflow routing
WorkflowService workflowService = new WorkflowService(interpreter);
get(API.USER_STUDY_WORKFLOW, new GetWorkflowRoute(workflowService), responseSerializer);
// User study announcements
get(API.USER_STUDY_ANNOUNCEMENTS, new GetUserAnnouncementsRoute(new I18nContentRenderer()), responseSerializer);
// User prequalifier instance route
StudyActivityDao studyActivityDao = new StudyActivityDao();
get(API.USER_STUDIES_PREQUALIFIER, new GetPrequalifierInstanceRoute(studyActivityDao, activityInstanceDao),
responseSerializer);
ConsentService consentService = new ConsentService(interpreter, studyActivityDao, new ConsentElectionDao());
MedicalRecordService medicalRecordService = new MedicalRecordService(consentService);
// User consent routes
get(API.USER_STUDIES_ALL_CONSENTS, new GetConsentSummariesRoute(consentService), responseSerializer);
get(API.USER_STUDIES_CONSENT, new GetConsentSummaryRoute(consentService), responseSerializer);
get(API.ACTIVITY_INSTANCE_STATUS_TYPE_LIST, new GetActivityInstanceStatusTypeListRoute(), responseSerializer);
// jenkins test
// User activity instance routes
get(API.USER_ACTIVITIES, new UserActivityInstanceListRoute(activityInstanceDao), responseSerializer);
post(API.USER_ACTIVITIES, new CreateActivityInstanceRoute(activityInstanceDao), responseSerializer);
get(API.USER_ACTIVITIES_INSTANCE, new GetActivityInstanceRoute(actInstService, activityInstanceDao), responseSerializer);
// User activity answers routes
FormActivityService formService = new FormActivityService(interpreter);
patch(API.USER_ACTIVITY_ANSWERS,
new PatchFormAnswersRoute(formService, activityInstanceDao, answerDao),
responseSerializer);
put(API.USER_ACTIVITY_ANSWERS, new PutFormAnswersRoute(workflowService, formInstanceDao, interpreter), responseSerializer);
// Study exit request
post(API.USER_STUDY_EXIT, new SendExitNotificationRoute());
// Study admin routes
before(API.ADMIN_BASE + "/*", new UserAuthCheckFilter());
get(API.ADMIN_STUDIES, new GetAdminStudiesRoute(studyAdminDao), responseSerializer);
get(API.ADMIN_WORKSPACES, new GetWorkspacesRoute(fireCloudExportService, studyAdminDao), responseSerializer);
post(API.EXPORT_STUDY, new ExportStudyRoute(fireCloudExportService, studyAdminDao), responseSerializer);
Config auth0Config = cfg.getConfig(ConfigFile.AUTH0);
before(API.DSM_BASE + "/*", new DsmAuthFilter(auth0Config.getString(ConfigFile.AUTH0_DSM_CLIENT_ID),
auth0Config.getString(ConfigFile.DOMAIN)));
get(API.DSM_ALL_KIT_REQUESTS, new GetDsmKitRequestsRoute(), responseSerializer);
get(API.DSM_KIT_REQUESTS_STARTING_AFTER, new GetDsmKitRequestsRoute(), responseSerializer);
get(API.DSM_STUDY_PARTICIPANT, new GetDsmStudyParticipant(), responseSerializer);
get(API.DSM_GET_INSTITUTION_REQUESTS, new GetDsmInstitutionRequestsRoute(), responseSerializer);
get(API.DSM_PARTICIPANT_MEDICAL_INFO, new GetDsmMedicalRecordRoute(medicalRecordService), responseSerializer);
get(API.DSM_PARTICIPANT_INSTITUTIONS, new GetDsmParticipantInstitutionsRoute(), responseSerializer);
post(API.DSM_NOTIFICATION, new SendDsmNotificationRoute(), responseSerializer);
post(API.DSM_TERMINATE_USER, new DsmExitUserRoute(), responseSerializer);
PdfService pdfService = new PdfService();
PdfBucketService pdfBucketService = new PdfBucketService(cfg);
PdfGenerationService pdfGenerationService = new PdfGenerationService();
get(API.DSM_PARTICIPANT_RELEASE_PDF, new GetDsmReleasePdfRoute(pdfService, pdfBucketService, pdfGenerationService));
get(API.DSM_PARTICIPANT_CONSENT_PDF, new GetDsmConsentPdfRoute(pdfService, pdfBucketService, pdfGenerationService));
get(API.DSM_ONDEMAND_ACTIVITIES, new GetDsmOnDemandActivitiesRoute(), responseSerializer);
get(API.DSM_ONDEMAND_ACTIVITY, new GetDsmTriggeredInstancesRoute(), responseSerializer);
post(API.DSM_ONDEMAND_ACTIVITY, new DsmTriggerOnDemandActivityRoute(), responseSerializer);
get(API.AUTOCOMPLETE_INSTITUTION, new GetInstitutionSuggestionsRoute(), responseSerializer);
get(API.LIST_CANCERS, new ListCancersRoute(new CancerService()), responseSerializer);
get(API.USER_MEDICAL_PROVIDERS, new GetMedicalProviderListRoute(), responseSerializer);
post(API.USER_MEDICAL_PROVIDERS, new PostMedicalProviderRoute(), responseSerializer);
patch(API.USER_MEDICAL_PROVIDER, new PatchMedicalProviderRoute(), responseSerializer);
delete(API.USER_MEDICAL_PROVIDER, new DeleteMedicalProviderRoute(), responseSerializer);
post(API.JOIN_MAILING_LIST, new JoinMailingListRoute());
get(API.GET_STUDY_MAILING_LIST, new GetMailingListRoute(), responseSerializer);
post(API.CHECK_IRB_PASSWORD, new CheckIrbPasswordRoute(), responseSerializer);
post(API.SEND_EMAIL, new SendEmailRoute(workflowService), responseSerializer);
get(API.POST_PASSWORD_RESET, new PostPasswordResetRoute(), responseSerializer);
get(API.DSM_DRUG_SUGGESTION, new GetDsmDrugSuggestionsRoute(DrugStore.getInstance()), responseSerializer);
// Routes calling DSM
URL dsmBaseUrl = null;
try {
dsmBaseUrl = new URL(cfg.getString(ConfigFile.DSM_BASE_URL));
} catch (MalformedURLException e) {
throw new RuntimeException("Invalid DSM URL {}. DSM-related routes will fail.", e);
}
DsmParticipantStatusService dsmParticipantStatusService = new DsmParticipantStatusService(dsmBaseUrl);
get(API.PARTICIPANT_STATUS, new GetDsmParticipantStatusRoute(dsmParticipantStatusService), responseSerializer);
get(API.STUDY_PASSWORD_REQUIREMENTS, new GetStudyPasswordRequirementsRoute(), responseSerializer);
patch(
API.UPDATE_USER_PASSWORD,
new UpdateUserPasswordRoute(),
responseSerializer
);
patch(
API.UPDATE_USER_EMAIL,
new UpdateUserEmailRoute(),
responseSerializer
);
Runnable runnable = () -> {
//load drug list
DsmDrugLoader drugLoader = new DsmDrugLoader();
drugLoader.fetchAndLoadDrugs(cfg.getString(ConfigFile.DSM_BASE_URL), cfg.getString(ConfigFile.DSM_JWT_SECRET));
//load cancer list
DsmCancerListService service = new DsmCancerListService(cfg.getString(ConfigFile.DSM_BASE_URL));
List<String> cancerNames = service.fetchCancerList(cfg.getString(ConfigFile.DSM_JWT_SECRET));
CancerStore.getInstance().populate(cancerNames);
LOG.info("Loaded {} cancers into pepper.", cancerNames == null ? 0 : cancerNames.size());
};
boolean runScheduler = cfg.getBoolean(ConfigFile.RUN_SCHEDULER);
if (runScheduler) {
Thread threadDL = new Thread(runnable);
threadDL.start();
//setup DDP JobScheduler on server startup
scheduler = JobScheduler.initializeWith(cfg,
DsmDrugLoaderJob::register,
DsmCancerLoaderJob::register);
} else {
LOG.info("DDP job scheduler is not set to run");
}
setupApiActivityFilter();
afterAfter(new MDCAttributeRemovalFilter(AddDDPAuthLoggingFilter.LOGGING_CLIENTID_PARAM,
AddDDPAuthLoggingFilter.LOGGING_USERID_PARAM,
MDC_STUDY,
MDC_ROUTE_CLASS,
X_FORWARDED_FOR,
MDCLogBreadCrumbFilter.LOG_BREADCRUMB));
awaitInitialization();
LOG.info("ddp startup complete");
}
private static void setupApiActivityFilter() {
afterAfter((Request request, Response response) -> {
String endpoint = MDC.get(MDC_ROUTE_CLASS);
if (endpoint == null) {
endpoint = "unknown";
}
String study = MDC.get(MDC_STUDY);
String httpMethod = request.requestMethod();
String participant = MDC.get(AddDDPAuthLoggingFilter.LOGGING_USERID_PARAM);
String client = MDC.get(AddDDPAuthLoggingFilter.LOGGING_CLIENTID_PARAM);
new StackdriverMetricsTracker(StackdriverCustomMetric.API_ACTIVITY,
study, endpoint, httpMethod, client, participant, response.status(),
PointsReducerFactory.buildSumReducer()).addPoint(1, Instant.now().toEpochMilli());
});
}
private static void setupMDC(String path, Route route) {
pathToClass.put(path, route.getClass().getSimpleName());
before(path, (request, response) -> MDC.put(MDC_ROUTE_CLASS, pathToClass.get(path)));
}
public static void get(String path, Route route, ResponseTransformer transformer) {
setupMDC(path, route);
Spark.get(path, route, transformer);
}
public static void get(String path, Route route) {
setupMDC(path, route);
Spark.get(path, route);
}
public static void post(String path, Route route) {
setupMDC(path, route);
Spark.post(path, route);
}
public static void post(String path, Route route, ResponseTransformer transformer) {
setupMDC(path, route);
Spark.post(path, route, transformer);
}
public static void put(String path, Route route) {
setupMDC(path, route);
Spark.put(path, route);
}
public static void put(String path, Route route, ResponseTransformer transformer) {
setupMDC(path, route);
Spark.put(path, route, transformer);
}
public static void patch(String path, Route route, ResponseTransformer transformer) {
setupMDC(path, route);
Spark.patch(path, route, transformer);
}
private static void setupCatchAllErrorHandling() {
//JSON for Not Found (code 404) handling
notFound((request, response) -> {
LOG.info("[404] Current status: {}", response.status());
ApiError apiError = new ApiError(ErrorCodes.NOT_FOUND, "This page was not found.");
response.type(ContentType.APPLICATION_JSON.getMimeType());
SimpleJsonTransformer jsonTransformer = new SimpleJsonTransformer();
return jsonTransformer.render(apiError);
});
internalServerError((request, response) -> {
ApiError apiError = new ApiError(ErrorCodes.SERVER_ERROR,
"Something unexpected happened.");
response.type(ContentType.APPLICATION_JSON.getMimeType());
SimpleJsonTransformer jsonTransformer = new SimpleJsonTransformer();
return jsonTransformer.render(apiError);
});
}
private static void enableCORS(final String origin, final String methods, final String headers) {
options("/*", (request, response) -> {
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if (accessControlRequestMethod != null) {
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
before((request, response) -> {
response.header("Access-Control-Allow-Origin", origin);
response.header("Access-Control-Request-Method", methods);
response.header("Access-Control-Allow-Headers", headers);
response.header("Access-Control-Allow-Credentials", "true");
response.type("application/json");
});
}
private static void initSqlCommands(Config sqlConfig) {
DBUtils.loadDaoSqlCommands(sqlConfig);
}
/**
* Allow to specify the exclusion of a path from the execution of a filter
*
* @param filterPath the path for which the filter is applicable
* @param pathsToExclude the paths to exclude the execution of the filter
* @param filter the filter
*/
public static void beforeWithExclusion(String filterPath, String[] pathsToExclude, Filter filter) {
before(filterPath, new ExcludePathFilterWrapper(filter, Arrays.asList(pathsToExclude)));
}
}
|
# Import Pandas
import pandas as pd
# Load Movies Metadata
metadata = pd.read_csv('../sample_data/movies_metadata.csv', low_memory=False)
# print(metadata['overview'].head())
# Import TfIdfVectorizer from scikit-learn
from sklearn.feature_extraction.text import TfidfVectorizer
# Define a TF-IDF Vectorizer Object. Remove all english stop words such as 'the', 'a'
tfidf = TfidfVectorizer(stop_words='english')
# Replace NaN with an empty string
metadata['overview'] = metadata['overview'].fillna('')
# Construct the required TF-IDF matrix by fitting and transforming the data
tfidf_matrix = tfidf.fit_transform(metadata['overview'])
# Output the shape of tfidf_matrix
# print('tfidf matrix: ', tfidf_matrix.shape)
# Array mapping from feature integer indices to feature name.
# print(tfidf.get_feature_names_out()[5000:5010])
# Import linear_kernel
from sklearn.metrics.pairwise import linear_kernel
# Compute the cosine similarity matrix
consine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)
# print(consine_sim.shape)
# print(consine_sim[1])
indices = pd.Series(metadata.index, index=metadata['title']).drop_duplicates()
print(indices[:10])
def get_recommendations(title, consine_sim=consine_sim):
idx = indices[title]
sim_scores = list(enumerate(consine_sim[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
sim_scores = sim_scores[1:11]
movie_indices = [i[0] for i in sim_scores]
return metadata['title'].iloc[movie_indices]
print(get_recommendations('The Dark Knight Rises'))
|
**命令:curl**
\\
在Linux中curl是一个利用URL规则在命令行下工作的文件传输工具,可以说是一款很强大的http命令行工具。它支持文件的上传和下载,是综合传输工具,但按传统,习惯称url为下载工具。\\
\\
语法:# curl [option] [url]\\
常见参数:\\
\\
<code>
-A/--user-agent <string> 设置用户代理发送给服务器
-b/--cookie <name=string/file> cookie字符串或文件读取位置
-c/--cookie-jar <file> 操作结束后把cookie写入到这个文件中
-C/--continue-at <offset> 断点续转
-D/--dump-header <file> 把header信息写入到该文件中
-e/--referer 来源网址
-f/--fail 连接失败时不显示http错误
-o/--output 把输出写到该文件中
-O/--remote-name 把输出写到该文件中,保留远程文件的文件名
-r/--range <range> 检索来自HTTP/1.1或FTP服务器字节范围
-s/--silent 静音模式。不输出任何东西
-T/--upload-file <file> 上传文件
-u/--user <user[:password]> 设置服务器的用户和密码
-w/--write-out [format] 什么输出完成后
-x/--proxy <host[:port]> 在给定的端口上使用HTTP代理
-#/--progress-bar 进度条显示当前的传送状态
</code>
1、基本用法\\
\\
执行后,www.linux.com 的html就会显示在屏幕上了\\
Ps:由于安装linux的时候很多时候是没有安装桌面的,也意味着没有浏览器,因此这个方法也经常用于测试一台服务器是否可以到达一个网站
\\
2、保存访问的网页\\
2.1:使用linux的重定向功能保存\\
\\
<code># curl http://www.linux.com >> linux.html</code>
2.2:可以使用curl的内置option:-o(小写)保存网页\\
\\
<code>$ curl -o linux.html http://www.linux.com</code>
执行完成后会显示如下界面,显示100%则表示保存成功\\
\\
<code>
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 79684 0 79684 0 0 3437k 0 --:--:-- --:--:-- --:--:-- 7781k
</code>
2.3:可以使用curl的内置option:-O(大写)保存网页中的文件\\
要注意这里后面的url要具体到某个文件,不然抓不下来\\
\\
<code># curl -O http://www.linux.com/hello.sh</code>
3、测试网页返回值\\
\\
<code># curl -o /dev/null -s -w %{http_code} www.linux.com</code>
Ps:在脚本中,这是很常见的测试网站是否正常的用法\\
\\
4、指定proxy服务器以及其端口\\
很多时候上网需要用到代理服务器(比如是使用代理服务器上网或者因为使用curl别人网站而被别人屏蔽IP地址的时候),幸运的是curl通过使用内置option:-x来支持设置代理\\
\\
<code># curl -x 192.168.100.100:1080 http://www.linux.com</code>
5、cookie\\
有些网站是使用cookie来记录session信息。对于chrome这样的浏览器,可以轻易处理cookie信息,但在curl中只要增加相关参数也是可以很容易的处理cookie\\
5.1:保存http的response里面的cookie信息。内置option:-c(小写)\\
\\
<code># curl -c cookiec.txt http://www.linux.com</code>
执行后cookie信息就被存到了cookiec.txt里面了\\
\\
5.2:保存http的response里面的header信息。内置option: -D\\
\\
<code># curl -D cookied.txt http://www.linux.com</code>
执行后cookie信息就被存到了cookied.txt里面了\\
\\
注意:-c(小写)产生的cookie和-D里面的cookie是不一样的。\\
\\
\\
http://www.cnblogs.com/duhuo/p/5695256.html
|
---
# 0.5 - API
# 2 - Release
# 3 - Contributing
# 5 - Template Page
# 10 - Default
search:
boost: 10
---
# Fanout Exchange
The **Fanout** Exchange is an even simpler, but slightly less popular way of routing in *RabbitMQ*. This type of `exchange` sends messages to all queues subscribed to it, ignoring any arguments of the message.
At the same time, if the queue listens to several consumers, messages will also be distributed among them.
## Example
```python linenums="1"
{! docs_src/rabbit/subscription/fanout.py !}
```
### Consumer Announcement
To begin with, we announced our **Fanout** exchange and several queues that will listen to it:
```python linenums="7" hl_lines="1"
{! docs_src/rabbit/subscription/fanout.py [ln:7-10] !}
```
Then we signed up several consumers using the advertised queues to the `exchange` we created:
```python linenums="13" hl_lines="1 6 11"
{! docs_src/rabbit/subscription/fanout.py [ln:13-25] !}
```
!!! note
`handler1` and `handler2` are subscribed to the same `exchange` using the same queue:
within a single service, this does not make sense, since messages will come to these handlers in turn.
Here we emulate the work of several consumers and load balancing between them.
### Message Distribution
Now the all messages will be send to all subscribers due they are binded to the same **FANOUT** exchange:
```python linenums="30"
{! docs_src/rabbit/subscription/fanout.py [ln:30.5,31.5,32.5,33.5] !}
```
---
!!! note
When sending messages to **Fanout** exchange, it makes no sense to specify the arguments `queue` or `routing_key`, because they will be ignored.
|
<template>
<div class="row" ref="inventory">
<div class="col s12 l6">
<div class="row">
<div class="col s12">
<div class="card">
<div class="card-content">
<span class="card-title">
Average age of ESXi servers {{ getAverageServersAge() }}
</span>
</div>
</div>
</div>
<div class="col s12">
<RAMbyHostsStatistics :esxiHosts="esxiHosts"/>
</div>
<div class="col s12 l6">
<PieChartRAMStatistics :esxiHosts="esxiHosts"/>
</div>
<div class="col s12 l6">
<CPUcoresCounter :esxiHosts="esxiHosts"/>
</div>
</div>
</div>
<div class="col s12 l6">
<div class="row">
<div class="col s12">
<CPUcoresStatistics :esxiHosts="esxiHosts"/>
</div>
<div class="col s12 m6">
<PoweredVmCounter />
<div class="card">
<div class="card-content">
<span class="card-title">Last installed VMs</span>
<div>
<button
class="btn waves-effect waves-light"
@click="showModal = true">
<span>Show all VMs</span>
</button>
</div>
<div class="row">
<table>
<tbody>
<tr v-for="vm in virtualMachines" :key="vm.id">
<td>{{ vm.name }}</td>
<td v-if="vm.os && vm.os.install_date">{{ vm.os.install_date }}</td>
<td v-else>-</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col s12 m6">
<InstancesByType />
<div class="card">
<div class="card-content">
<span class="card-title">Last created instances</span>
<div class="row">
<table>
<tbody>
<tr v-for="instance in instances" :key="instance.id">
<td> {{ instance.name }} </td>
<td> {{ $date(instance.created_on).toHuman() }} </td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<Modal v-if="showModal" @close="showModal=false">
<template v-slot:header></template>
<template v-slot:content>
<h2>All Virtual Machines</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Installation Date</th>
</tr>
</thead>
<tbody>
<tr v-for="vm in allVirtualMachines" :key="vm.id">
<td>{{ vm.name }}</td>
<td>{{ vm.os.install_date }}</td>
</tr>
</tbody>
</table>
</template>
</Modal>
</div>
</template>
<script>
import CPUcoresCounter from './statistics/CPUcoresCounter';
import CPUcoresStatistics from './statistics/CPUcoresStatistics';
import RAMbyHostsStatistics from './statistics/RAMbyHostsStatistics';
import PieChartRAMStatistics from './statistics/PieChartRAMStatistics';
import PoweredVmCounter from './statistics/PoweredVmCounter';
import InstancesByType from './statistics/InstancesByType';
export default {
components: {
CPUcoresCounter,
CPUcoresStatistics,
RAMbyHostsStatistics,
PieChartRAMStatistics,
InstancesByType,
PoweredVmCounter,
},
data() {
return {
showModal: false,
};
},
computed: {
esxiHosts() {
return this.$store.state.esxi.esxiHosts;
},
virtualMachines() {
return this.$store.getters['esxi/getLatestvirtualMachines'];
},
instances() {
return this.$store.getters['esxi/getLastCreated']('instances');
},
allVirtualMachines() {
return this.$store.getters['esxi/getAllVirtualMachines'];
},
},
methods: {
getData() {
const loader = this.$loading.show({ container: this.$refs.inventory });
const promise1 = this.$store.dispatch('esxi/getEsxiHosts');
const promise2 = this.$store.dispatch('esxi/getVirtualMachines');
const promise3 = this.$store.dispatch('esxi/getInstances');
Promise.all([promise1, promise2, promise3])
.finally(() => loader.hide());
},
getAverageServersAge() {
let count = 0;
let seconds = 0;
this.esxiHosts.forEach((e) => {
if (e.usage_type === 'worker') {
if (e.purchase_date) {
count += 1;
seconds += Math.floor(Date.now() / 1000) - e.purchase_date;
}
}
});
const average = Math.floor(seconds / count);
const years = Math.floor(average / 31536000);
const months = Math.floor((average % 31536000) / 2628000);
const days = Math.floor(((average % 31536000) % 2628000) / 86400);
return ` - ${years ? `${years} years` : ''} ${months ? `${months} months` : ''} ${days ? `${days} days` : ''}`;
},
},
created() {
this.getData();
},
};
</script>
|
import Models
import Services
import SwiftUI
import Views
import WebKit
import Utils
struct SafariWebLink: Identifiable {
let id: UUID
let url: URL
}
@MainActor final class WebReaderViewModel: ObservableObject {
@Published var articleContent: ArticleContent?
@Published var errorMessage: String?
@Published var allowRetry = false
@Published var isDownloadingAudio: Bool = false
@Published var audioDownloadTask: Task<Void, Error>?
@Published var operationMessage: String?
@Published var showOperationToast: Bool = false
@Published var operationStatus: OperationStatus = .none
@Published var explainText: String?
func hasOriginalUrl(_ item: Models.LibraryItem) -> Bool {
if let pageURLString = item.pageURLString, let host = URL(string: pageURLString)?.host {
if host == "omnivore.app" {
return false
}
return true
}
return false
}
func downloadAudio(audioController: AudioController, item: Models.LibraryItem) {
Snackbar.show(message: "Downloading Offline Audio", dismissAfter: 2000)
isDownloadingAudio = true
if let audioDownloadTask = audioDownloadTask {
audioDownloadTask.cancel()
}
let itemID = item.unwrappedID
audioDownloadTask = Task.detached(priority: .background) {
let canceled = Task.isCancelled
let downloaded = await audioController.downloadForOffline(itemID: itemID)
DispatchQueue.main.async {
self.isDownloadingAudio = false
if !canceled {
Snackbar.show(message: downloaded ? "Audio file downloaded" : "Error downloading audio", dismissAfter: 2000)
}
}
}
}
func loadContent(dataService: DataService, username: String, itemID: String, retryCount _: Int = 0) async {
errorMessage = nil
do {
articleContent = try await dataService.loadArticleContentWithRetries(itemID: itemID, username: username)
} catch {
if let fetchError = error as? ContentFetchError {
allowRetry = true
switch fetchError {
case .network:
errorMessage = "We were unable to retrieve your content. Please check network connectivity and try again."
default:
errorMessage = "We were unable to parse your content."
}
} else {
errorMessage = "We were unable to retrieve your content."
}
}
}
func createHighlight(
messageBody: [String: Any],
replyHandler: @escaping WKScriptMessageReplyHandler,
dataService: DataService
) {
let result = dataService.createHighlight(
shortId: messageBody["shortId"] as? String ?? "",
highlightID: messageBody["id"] as? String ?? "",
quote: messageBody["quote"] as? String ?? "",
patch: messageBody["patch"] as? String ?? "",
articleId: messageBody["articleId"] as? String ?? "",
positionPercent: messageBody["highlightPositionPercent"] as? Double,
positionAnchorIndex: messageBody["highlightPositionAnchorIndex"] as? Int,
annotation: messageBody["annotation"] as? String ?? ""
)
return replyHandler(["result": result], nil)
}
func deleteHighlight(
messageBody: [String: Any],
replyHandler: @escaping WKScriptMessageReplyHandler,
dataService: DataService
) {
if let highlightID = messageBody["highlightId"] as? String {
dataService.deleteHighlight(highlightID: highlightID)
replyHandler(["result": true], nil)
} else {
replyHandler(["result": false], nil)
}
}
func mergeHighlight(
messageBody: [String: Any],
replyHandler: @escaping WKScriptMessageReplyHandler,
dataService: DataService
) {
guard
let shortId = messageBody["shortId"] as? String,
let highlightID = messageBody["id"] as? String,
let quote = messageBody["quote"] as? String,
let patch = messageBody["patch"] as? String,
let articleId = messageBody["articleId"] as? String,
let overlapHighlightIdList = messageBody["overlapHighlightIdList"] as? [String],
let positionPercent = messageBody["highlightPositionPercent"] as? Double,
let positionAnchorIndex = messageBody["highlightPositionAnchorIndex"] as? Int
else {
replyHandler([], "createHighlight: Error encoding response")
return
}
let jsonHighlight = dataService.mergeHighlights(
shortId: shortId,
highlightID: highlightID,
quote: quote,
patch: patch,
articleId: articleId,
positionPercent: positionPercent,
positionAnchorIndex: positionAnchorIndex,
overlapHighlightIdList: overlapHighlightIdList
)
replyHandler(["result": jsonHighlight], nil)
}
func updateHighlight(
messageBody: [String: Any],
replyHandler: @escaping WKScriptMessageReplyHandler,
dataService: DataService
) {
let highlightID = messageBody["highlightId"] as? String
let annotation = messageBody["annotation"] as? String
if let highlightID = highlightID, let annotation = annotation {
dataService.updateHighlightAttributes(highlightID: highlightID, annotation: annotation)
replyHandler(["result": highlightID], nil)
} else {
replyHandler([], "updateHighlight: Error encoding response")
}
}
func updateReadingProgress(
messageBody: [String: Any],
replyHandler: @escaping WKScriptMessageReplyHandler,
dataService: DataService
) {
let itemID = messageBody["id"] as? String
let readingProgress = messageBody["readingProgressPercent"] as? Double
let anchorIndex = messageBody["readingProgressAnchorIndex"] as? Int
print("READING PROGRESS FROM JS: ", messageBody)
guard let itemID = itemID, let readingProgress = readingProgress, let anchorIndex = anchorIndex else {
replyHandler(["result": false], nil)
return
}
dataService.updateLinkReadingProgress(itemID: itemID, readingProgress: readingProgress, anchorIndex: anchorIndex, force: false)
replyHandler(["result": true], nil)
}
func webViewActionWithReplyHandler(
message: WKScriptMessage,
replyHandler: @escaping WKScriptMessageReplyHandler,
dataService: DataService
) {
guard let messageBody = message.body as? [String: Any] else { return }
guard let actionID = messageBody["actionID"] as? String else { return }
switch actionID {
case "deleteHighlight":
deleteHighlight(messageBody: messageBody, replyHandler: replyHandler, dataService: dataService)
case "createHighlight":
createHighlight(messageBody: messageBody, replyHandler: replyHandler, dataService: dataService)
case "mergeHighlight":
mergeHighlight(messageBody: messageBody, replyHandler: replyHandler, dataService: dataService)
case "updateHighlight":
updateHighlight(messageBody: messageBody, replyHandler: replyHandler, dataService: dataService)
case "articleReadingProgress":
updateReadingProgress(messageBody: messageBody, replyHandler: replyHandler, dataService: dataService)
default:
replyHandler(nil, "Unknown actionID: \(actionID)")
}
}
func setLabelsForHighlight(
highlightID: String,
labelIDs: [String],
dataService: DataService
) {
dataService.setLabelsForHighlight(highlightID: highlightID, labelIDs: labelIDs)
}
func saveLink(dataService: DataService, url: URL) {
Task {
do {
Snackbar.show(message: "Saving link", dismissAfter: 5000)
_ = try await dataService.createPageFromUrl(id: UUID().uuidString, url: url.absoluteString)
Snackbar.show(message: "Link saved", dismissAfter: 2000)
} catch {
Snackbar.show(message: "Error saving link", dismissAfter: 2000)
}
}
}
func saveLinkAndFetch(dataService: DataService, username: String, url: URL) {
Task {
do {
Snackbar.show(message: "Saving link", dismissAfter: 5000)
let requestId = UUID().uuidString
_ = try await dataService.createPageFromUrl(id: requestId, url: url.absoluteString)
Snackbar.show(message: "Link saved", dismissAfter: 2000)
await loadContent(dataService: dataService, username: username, itemID: requestId, retryCount: 0)
} catch {
Snackbar.show(message: "Error saving link", dismissAfter: 2000)
}
}
}
func trackReadEvent(item: Models.LibraryItem) {
let itemID = item.unwrappedID
let slug = item.unwrappedSlug
let originalArticleURL = item.unwrappedPageURLString
EventTracker.track(
.linkRead(
linkID: itemID,
slug: slug,
reader: "WEB",
originalArticleURL: originalArticleURL
)
)
}
}
|
import unittest
from unittest import TestCase
from certification_script import read_from_file, convert_to_float, compare, certificate, create_and_write_to_xlsx
import pytest
class Test(TestCase):
"""
Тесты для certification_automation.py
"""
@pytest.fixture(autouse=True)
def _pass_fixtures(self, capsys):
self.capsys = capsys
def test_read_error(self):
file_path = 'А_нет_такого_файла.xlsx'
sheet_name = 'Оценка компетенций'
result = read_from_file(file_path, sheet_name, 11, 30, 10)
captured = self.capsys.readouterr()
self.assertEqual((
'Error while reading from file: [Errno 2] No such file or '"directory: 'А_нет_такого_файла.xlsx'\n"),
captured.out)
def test_convert_error(self):
result = convert_to_float(1) # если на вход подан вообще не список
captured = self.capsys.readouterr()
self.assertEqual("Error TWO while converting to float: 'int' object is not iterable\n", captured.out)
def test_convert_error_2(self):
result = convert_to_float("A") # если на вход подано не числовое значение
captured = self.capsys.readouterr()
self.assertEqual("Error ONE while converting to float: could not convert string to float: 'A'\n", captured.out)
def test_both(self):
file_path = 'Test_file_1.xlsx'
sheet_name = 'Оценка компетенций'
result = read_from_file(file_path, sheet_name, 11, 30, 10)
expected_values = [1.1, 2.1, 3.1, 4.0, 5.0, 6.1, 7.2, 8.6, 9.0, 0.0, 11.0, 12.0, 13.0, 0.0, 15.2, 16.0, 0.0,
0.0, 0.0, 0.0]
self.assertEqual(convert_to_float(result), expected_values)
def test_empty_cells(self):
file_path = 'Test_file_1.xlsx'
sheet_name = 'Оценка компетенций'
result = read_from_file(file_path, sheet_name, 11, 12, 11)
expected_values = [0.0, 0.0]
self.assertEqual(convert_to_float(result), expected_values)
def test_bad_file(self):
file_path = 'А_нет_такого_файла.xlsx'
sheet_name = 'Оценка компетенций'
result = read_from_file(file_path, sheet_name, 11, 30, 10)
self.assertEqual(result, [])
def test_convert_to_float(self):
test_values = ['1.1', 4, 2.1, '', None] # еще раз тестируем на все возможные вариации ввода
result = convert_to_float(test_values)
self.assertEqual(result, [1.1, 4.0, 2.1, 0.0, 0.0])
def test_convert_to_float_2(self):
result = convert_to_float(1)
self.assertEqual(result, [])
def test_compare(self):
test_average = [1.1, 1.4, 1.5, 1.6, 1.0, 1.0, 1.3, 1.0, 2.1, 0.0, 1.0, 1.0, 2.0, 2.1, 1.0, 1.0]
test_target = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0]
self.assertTrue(compare(test_average, test_target, 0.8), True)
def test_certificate(self):
file_path = 'Test_file_2.xlsx'
sheet_name = 'Оценка компетенций'
file_path_2 = 'Компетенции_по_шкале_DE.xlsx'
sheet_name_2 = 'Целевые значения'
res = certificate(file_path, sheet_name, file_path_2, sheet_name_2, False)
self.assertEqual({'Junior I': (False, 0.78), 'Junior II': (False, 0.78), 'Middle I': (False, 0.72),
'Middle II': (False, 0.72), 'Senior I': (False, 0.67), 'Senior II ': (False, 0.28), 'Expert ': (False, 0.11)}, res)
def test_create_and_write_to_xlsx(self):
save_to = 'C:/Users/user/PycharmProjects/certification_automation'
res = {'Junior I': (True, 1.0), 'Junior II': (True, 0.94), 'Middle I': (True, 0.89), 'Middle II': (True, 0.83),
'Senior I': (True, 0.83), 'Senior II ': (False, 0.78), 'Expert ': (False, 0.78)}
create_and_write_to_xlsx("Меня нет я тест", res, save_to)
captured = self.capsys.readouterr()
self.assertEqual('Файл '"'C:/Users/user/PycharmProjects/certification_automation/certificate_Меня нет "
"я тест.xlsx' создан, данные занесены.\n", captured.out)
if __name__ == '__main__':
unittest.main()
|
package com.msawady.tandemtrack.db
import cats.effect.IO
import cats.syntax.all.*
import com.msawady.tandemtrack.models.User
import com.msawady.tandemtrack.models.User.UserId
import skunk.*
import skunk.data.*
import skunk.codec.*
import skunk.codec.all.varchar
import skunk.implicits.*
object UserDao {
val idCodec: Codec[UserId] = Codec.simple(_.value, _.toString.asRight.map(UserId.apply), Type.varchar)
val userCodec: Codec[User] = (idCodec *: varchar *: varchar).to[User]
def insert(user: User): IO[Unit] = {
val enc = userCodec.values
val c = sql"""
INSERT INTO "user" (id, name, email)
VALUES $userCodec.values
""".command
SkunkSession.session.use(s => s.prepare(c).flatMap(_.execute(user))).void
}
def findById(id: UserId): IO[Option[User]] = {
val q: Query[UserId, Option[User]] =
sql"""
SELECT * FROM "user" WHERE id = $idCodec
""".query(userCodec.opt)
SkunkSession.session.use(s => s.prepare(q).flatMap(q => q.unique(id)))
}
def deleteById(id: UserId): IO[Unit] = {
val q: Command[UserId] =
sql"""
DELETE FROM "user" WHERE id = $idCodec
""".command
SkunkSession.session.use(s => s.prepare(q).flatMap(_.execute(id))).void
}
}
|
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {LoginComponent} from './auth/login/login.component';
import {RegisterComponent} from './auth/register/register.component';
import {AuthGuardService} from './auth/auth-guard.service';
const routes: Routes = [
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
{
path:'',
loadChildren: './credit-debit/credit-debit.module#CreditDebitModule',
canLoad:[AuthGuardService]
},
{path: '**', redirectTo: ''}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
|
#' Generate table with random values
#'
#' @param n_rows Number of rows.
#'
generate_data <- function(r_rows) {
tibble(
V01 = rbeta(r_rows, shape1 = 1.5, shape2 = 0.9),
V02 = rbeta(r_rows, shape1 = 0.9, shape2 = 1.5),
V03 = rbeta(r_rows, shape1 = 1, shape2 = 2),
V04 = rnorm(r_rows),
V05 = c(rnorm(r_rows/2), rnorm(r_rows/2, 5, 0.5)),
V06 = rgamma(r_rows, shape = 3),
V07 = rgamma(r_rows, shape = 6),
V08 = rgamma(r_rows, shape = 9),
V09 = rgamma(r_rows, shape = 12),
V10 = c(rnorm(r_rows/2), rnorm(r_rows/2, 5)),
V11 = rweibull(r_rows, 4),
V12 = rweibull(r_rows, 6),
V13 = rweibull(r_rows, 8),
V14 = rweibull(r_rows, 10),
V15 = rchisq(r_rows, 3),
V16 = rchisq(r_rows, 4),
V17 = rchisq(r_rows, 5),
V18 = rchisq(r_rows, 6),
V19 = rchisq(r_rows, 7),
V20 = rf(r_rows, 100, 100)
) %>%
round(2)
}
#' Get `hist()` output
#'
#' @param x Values.
#' @param bins Number of bins.
#'
get_hist <- function(x, bins = 21) {
h <- hist(x, breaks = seq(min(x), max(x), length.out = bins), plot = FALSE)
h
}
#' Min-max normalization
#'
#' @param x Values.
#' @param min Min value.
#' @param max Max value.
#'
min_max_normalization <- function(x, min = 1, max = 30) {
min_max_norm <- (x - min(x)) / (max(x) - min(x))
round((max-min) * min_max_norm + min)
}
#' Create histogram table
#'
#' @param mm_norm_counts Min-max normalized counts.
#' @param n_rows_pg Number of rows of a page.
#' @param n_rows_da Number of rows of a table.
#' @param empty Logical. If TRUE all values are zero.
#' @param col_prefix Column name prefix.
#'
get_hist_table <- function(mm_norm_counts,
n_rows_pg,
n_rows_da,
empty = FALSE,
col_prefix = "T") {
da <-
map(mm_norm_counts, ~{
v <- rep(0, n_rows_pg)
if (!empty) {
v[1:.x] <- 1
}
rev(v)
}) %>%
set_names(paste0(col_prefix, seq_along(mm_norm_counts))) %>%
as_tibble()
n_iter <- ceiling(n_rows_da / n_rows_pg)
l_da <- map(1:n_iter, ~{da})
da <- do.call(rbind, l_da)
da[1:n_rows_da, ]
}
#' Get y-axis frequencies values
#'
#' @param n_rows Number of rows of a table.
#' @param h `hist()` output.
#' @param pg_len Page length.
#'
get_y_axis_freq_values <- function(n_rows, h, pg_len) {
h_counts <- round(seq(min(h$counts), max(h$counts), length.out = pg_len))
h_counts_tmp <- rep(NA_real_, length(h_counts))
h_counts_tmp[seq(1, length(h_counts), 3)] <- h_counts[seq(1, length(h_counts), 3)]
h_counts <- rev(h_counts_tmp)
h_counts <- rep(h_counts, ceiling(n_rows / length(h$mids)))[1:n_rows]
h_counts
}
#' Get x-axis values
#'
#' @param data Data.
#' @param empty_data Data with zeros.
#' @param values Vector of values.
#'
get_x_axis_values <- function(data, empty_data, values) {
x_axis_data <- data[1, ]
n_cols <- ncol(data)
x_axis_data[1, ] <- matrix(values, ncol = n_cols)
x_axis_data
}
#' Get x-axis row indices
#'
#' @param data Data.
#' @param pg_len Page length.
#'
get_x_axis_row_ids <- function(data, pg_len) {
ids <- seq(1, nrow(data), pg_len)
ids_len <- length(ids) - 1
ids <- ids + lag(0:ids_len)
ids[-1]
}
#' Insert x-axis values into data
#'
#' @param data Main table.
#' @param x_axis_values Data returned from `get_x_axis_values()` function.
#' @param x_axis_ids x-axis values indices.
#'
insert_x_axis_values <- function(data, x_axis_values, x_axis_ids) {
for (i in x_axis_ids) {
data <- data %>% add_row(x_axis_values, .before = i)
}
data
}
#' Set target data values
#'
#' @param target_data Target data.
#' @param selected_col Index of selected column.
#'
set_target_values <- function(target_data, selected_col) {
sel_col_vals <- target_data[[selected_col]]
target_data[sel_col_vals == 0, selected_col] <- -1
target_data[sel_col_vals != 0, selected_col] <- 2
target_data[, -selected_col] <- target_data[, -selected_col] * 10 + 11
target_data
}
#' Create DT table
#'
#' @param values_data Data with values.
#' @param empty_data Data with zeros.
#' @param t_freq_data Target freq data.
#' @param pal Color pallet.
#'
#' @details
#' color palette
#'
#' pal[1] | #8d99ae
#' - hist background color
#' - cell text color
#'
#' pal[2] | #edf2f4
#' - background
#' - hist cell text color
#'
#' pal[3] | #2b2d42
#' - selected column
#' - table header
#' - x-axis
#' - y-axis
create_dt_table <- function(data, values_data, empty_data, t_freq_data, pal) {
brks_1 <- c(0, 1, 10, 20, 100, 200)
brks_2 <- c(-1, 0, 1, 10, 20, 100, 200)
bg_clrs_1 <- c(pal[2], pal[1], pal[1], pal[2], pal[1], pal[2], pal[2])
clrs <- c(pal[3], pal[1], pal[2], pal[3], pal[1], pal[2], pal[2], pal[3])
fnt_w <- c("bold", "normal", "normal", "bold", "normal", "normal", "normal", "bold")
fnt_s <- c("12px", "10px", "10px", "12px", "10px", "10px", "10px", "12px")
brd_lr <- c(stringr::str_glue("2px solid {pal[3]}"), "none", "none",
stringr::str_glue("2px solid {pal[3]}"), "none", "none", "none", "none")
tar_start <- 1 + ncol(values_data)
tar_end <- tar_start + ncol(empty_data)
data %>%
DT::datatable(
style = "bootstrap4",
class = "hover",
rownames = FALSE,
colnames = c(" ", colnames(values_data), colnames(t_freq_data), colnames(empty_data)),
selection = list(target = 'column', mode = 'single'),
callback = DT::JS(stringr::str_glue(
"$('table.dataTable.no-footer').css('border', '3px solid {pal[2]}');"
)),
options = list(
headerCallback = DT::JS(stringr::str_glue(
"function(thead) {{",
" $(thead).css('font-size', '14px');",
" $(thead).closest('thead').find('th').css('border-bottom', '2px solid {pal[3]}');",
" $(thead).closest('thead').find('th').css('background', '{pal[2]}');",
" $(thead).closest('thead').find('th').css('color', '{pal[3]}');",
" $(thead).closest('thead').find('th').css('text-align', 'center');",
" $(thead).closest('thead').find('th').css('padding', '3px');",
"}}"
)),
initComplete = JS(
"function(settings, json) {",
"$('body').css({'font-family': 'Courier'});",
"}"
),
pagingType = "simple",
columnDefs = list(list(targets = tar_start:tar_end, visible = FALSE)),
pageLength = pg_len + 1,
ordering = FALSE,
dom = "tp"
)) %>%
formatStyle(columns = 1:ncol(data),
padding = "1px",
`font-size` = "10px",
`line-height` = "16px",
`vertical-align` = "middle",
`border-top` = "0px",
`text-align` = "center") %>%
formatStyle(columns = 1:(ncol(values_data)+1),
valueColumns = c(names(t_freq_data), names(empty_data)),
color = styleInterval(brks_2, clrs),
backgroundColor = styleInterval(brks_1, bg_clrs_1),
fontSize = styleInterval(brks_2, fnt_s),
fontWeight = styleInterval(brks_2, fnt_w),
borderLeft = styleInterval(brks_2, brd_lr),
borderRight = styleInterval(brks_2, brd_lr)
)
}
|
> Задача 1. Да се намери резултатът от изпълнението на програмата:
```c++
#include<iostream>
using namespace std;
class A{
public:
void printMessage();
};
void A::printMessage(){
cout<< "Hello!\n"<<endl;
}
int main(){
A a;
a.printMessage();
return 0;
}
```
> Задача 2. Да се намери резултатът от изпълнението на програмата:
```c++
#include<iostream>
using namespace std;
class C{
public:
int a;
int b;
void init(int,int);
};
void C::init(int x, int y){
a = x + 1;
b = y - 3;
}
int main(){
C c;
c.init(4,6);
cout << c.a << " " << c.b << endl;
return 0;
}
```
> Задача 3. Да сe дефинира клас Absolute, чрез който да се намери абсолютната стойност на цяло и на реално число.
> Задача 4. Напишете структура Programmer, която има следните член-данни: име - символен низ до 20 символа; брой езици, които знае - цяло число; заплата - цяло число. Напишете следните методи за Programmer: void read() - прочита член-данните от клавиатурата; void print() - извежда на екрана член-данните; bool correctData() - проверява дали член-данните са коректни - т.е. числата са положителни
> Задача 5. Нека е дадена структурата "Person", съдържаща единствена член-данна - цяло число "age": Да се реализира функция Person * readPeople(ifstream &f), която получава файлов поток за вход, съдърщаш цяло число n и n на брой записани инстанции на Person и връща указател към масив от Person с n елемента, съответстващи на n-те инстанции, записани във файла. Да се реализира функция void writePeople(int n, Person * ppl, ofstream &f), която получава цяло число n, указател към масив от Person с n елемента и файлов поток за изход, след което записва числото n, последвано от всички елементи в масива в подадения поток.
```c++
struct Person {
int age;
};
```
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IDepositController} from "../interfaces/IDepositController.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IMerkleTreeVerifier} from "../lithium/interfaces/IMerkleTreeVerifier.sol";
import {IPortfolio} from "../interfaces/IPortfolio.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
contract MerkleTreeVerifierDepositController is IDepositController, Initializable {
using SafeERC20 for IERC20Metadata;
IMerkleTreeVerifier public lenderVerifier;
uint256 public allowListIndex;
function initialize(IMerkleTreeVerifier _lenderVerifier, uint256 _allowListIndex) external initializer {
lenderVerifier = _lenderVerifier;
allowListIndex = _allowListIndex;
}
function maxDeposit(address) public view virtual returns (uint256) {
return IPortfolio(msg.sender).maxSize() - IPortfolio(msg.sender).totalAssets();
}
function maxMint(address receiver) public view virtual returns (uint256) {
return previewDeposit(maxDeposit(receiver));
}
function previewDeposit(uint256 assets) public view returns (uint256 shares) {
return IPortfolio(msg.sender).convertToShares(assets);
}
function previewMint(uint256 shares) public view returns (uint256) {
uint256 totalAssets = IPortfolio(msg.sender).totalAssets();
uint256 totalSupply = IPortfolio(msg.sender).totalSupply();
if (totalSupply == 0) {
return shares;
} else {
return Math.ceilDiv((shares * totalAssets), totalSupply);
}
}
function onDeposit(
address sender,
uint256 assets,
address
) public view virtual override returns (uint256, uint256) {
require(sender == address(this), "MerkleTreeVerifierDepositController: Trying to bypass controller");
return (previewDeposit(assets), 0);
}
function onMint(
address sender,
uint256 shares,
address
) public view virtual override returns (uint256, uint256) {
require(sender == address(this), "MerkleTreeVerifierDepositController: Trying to bypass controller");
return (previewMint(shares), 0);
}
function deposit(
IPortfolio portfolio,
uint256 amount,
bytes32[] calldata merkleProof
) public {
require(
lenderVerifier.verify(allowListIndex, keccak256(abi.encodePacked(msg.sender)), merkleProof),
"MerkleTreeVerifierDepositController: Invalid proof"
);
portfolio.asset().safeTransferFrom(msg.sender, address(this), amount);
portfolio.asset().approve(address(portfolio), amount);
portfolio.deposit(amount, msg.sender);
}
function mint(
IPortfolio portfolio,
uint256 shares,
bytes32[] calldata merkleProof
) public {
require(
lenderVerifier.verify(allowListIndex, keccak256(abi.encodePacked(msg.sender)), merkleProof),
"MerkleTreeVerifierDepositController: Invalid proof"
);
uint256 assets = portfolio.previewMint(shares);
portfolio.asset().safeTransferFrom(msg.sender, address(this), assets);
portfolio.asset().approve(address(portfolio), assets);
portfolio.deposit(assets, msg.sender);
}
}
|
import { format } from 'date-fns';
import React, { useEffect, useState } from 'react';
import BookingModal from './BookingModal';
import Service from './Service';
const AvailableAppoinment = ({ date }) => {
const [services, setServices] = useState([]);
const [treatment, setTreatment] = useState({});
useEffect(() => {
fetch('http://localhost:5000/service')
.then(res => res.json())
.then(data => setServices(data));
}, [])
return (
<div>
<h1 className='text-primary font-bold text-2xl text-center'>Available appoinment on {format(date, 'PP')}</h1>
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5'>
{
services.map(service => <Service key={service._id} service={service} setTreatment={setTreatment}></Service>)
}
</div>
<div>
{
treatment && <BookingModal treatment={treatment} date={date} setTreatment={setTreatment}></BookingModal>
}
</div>
</div>
);
};
export default AvailableAppoinment;
|
<template>
<el-row :gutter="20">
<el-col :span="6">
<el-card shadow="hover" :body-style="{ padding: '0px' }">
<div class="card-content">
<div class="card-left">
<el-icon><user /></el-icon>
</div>
<div class="card-right">
<div class="card-num">{{ userCount }}</div>
<div>用户总数</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover" :body-style="{ padding: '0px' }">
<div class="card-content">
<div class="card-left">
<el-icon><headset /></el-icon>
</div>
<div class="card-right">
<div class="card-num">{{ songCount }}</div>
<div>歌曲总数</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover" :body-style="{ padding: '0px' }">
<div class="card-content">
<div class="card-left">
<el-icon><mic /></el-icon>
</div>
<div class="card-right">
<div class="card-num">{{ singerCount }}</div>
<div>歌手数量</div>
</div>
</div>
</el-card>
</el-col>
<el-col :span="6">
<el-card shadow="hover" :body-style="{ padding: '0px' }">
<div class="card-content">
<div class="card-left">
<el-icon><document /></el-icon>
</div>
<div class="card-right">
<div class="card-num">{{ songListCount }}</div>
<div>歌单数量</div>
</div>
</div>
</el-card>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<h3>用户性别比例</h3>
<el-card class="cav-info" shadow="hover" :body-style="{ padding: '0px' }" id="userSex"></el-card>
</el-col>
<el-col :span="12">
<h3>歌单类型</h3>
<el-card class="cav-info" shadow="hover" :body-style="{ padding: '0px' }" id="songStyle"></el-card>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<h3>歌手性别比例</h3>
<el-card class="cav-info" shadow="hover" :body-style="{ padding: '0px' }" id="singerSex"></el-card>
</el-col>
<el-col :span="12">
<h3>歌手国籍</h3>
<el-card class="cav-info" shadow="hover" :body-style="{ padding: '0px' }" id="country"></el-card>
</el-col>
</el-row>
</template>
<script setup lang="ts">
import {HttpManager} from "@/api/request";
import * as echarts from "echarts";
import { Mic, Document, User, Headset } from "@element-plus/icons-vue";
//<editor-fold desc="动态页面">
const resize = () => {
userSexChart.resize();
singerSexChart.resize();
countryChart.resize();
songStyleChart.resize();
}
onMounted(() => {
window.addEventListener("resize", resize)
})
onBeforeUnmount(() => {
window.removeEventListener("resize",resize)
})
//</editor-fold>
//<editor-fold desc="utils">
function setSex(sex:number, arr: any) {
let value = 0;
const name = sex === 0 ? "男" : "女";
for (let item of arr) {
if (sex === item.sex) {
value++;
}
}
return { value, name };
}
//</editor-fold>
//<editor-fold desc="用户相关">
const userCount = ref(0);
let userSexChart: any;
const userSex = reactive({
series: [
{
type: "pie",
data: [
{
value: 0,
name: "男",
},
{
value: 0,
name: "女",
},
],
},
],
});
HttpManager.getAllConsumer().then((result) => {
userCount.value = result.data.length;
userSex.series[0].data.push(setSex(0, result.data));
userSex.series[0].data.push(setSex(1, result.data));
userSexChart = echarts.init(document.getElementById("userSex")!);
userSexChart.setOption(userSex);
});
//</editor-fold>
//<editor-fold desc="歌曲相关">
const songCount = ref(0);
HttpManager.getAllSong().then((res) => {
songCount.value = res.data.length;
});
//</editor-fold>
//</editor-fold>//<editor-fold desc="歌手相关">
let singerSexChart: any;
let countryChart: any;
const singerCount = ref(0);
const singerSex = reactive({
series: [
{
type: "pie",
data: [
{
value: 0,
name: "男",
},
{
value: 0,
name: "女",
},
],
},
],
});
const country = reactive({
xAxis: {
type: "category",
data: [
"中国",
"韩国",
"意大利",
"新加坡",
"美国",
// "马来西亚",
"西班牙",
"日本",
],
},
yAxis: {
type: "value",
},
series: [
{
data: [0, 0, 0, 0, 0, 0, 0, 0],
type: "bar",
barWidth: "20%",
},
],
});
HttpManager.getAllSinger().then((result) => {
singerCount.value = result.data.length;
singerSex.series[0].data.push(setSex(0, result.data));
singerSex.series[0].data.push(setSex(1, result.data));
singerSexChart = echarts.init(document.getElementById("singerSex")!);
singerSexChart.setOption(singerSex);
for (let item of result.data) {
for (let i = 0; i < country.xAxis.data.length; i++) {
if (item.location.includes(country.xAxis.data[i])) {
country.series[0].data[i]++;
break;
}
}
}
countryChart = echarts.init(document.getElementById("country")!);
countryChart.setOption(country);
});
//</editor-fold>
//<editor-fold desc="歌单相关">
let songStyleChart : any;
const songListCount = ref(0);
const songStyle = reactive({
xAxis: {
type: "category",
data: ["华语", "粤语", "欧美", "日韩", "BGM", "轻音乐", "乐器"],
},
yAxis: {
type: "value",
},
series: [
{
data: [0, 0, 0, 0, 0, 0, 0],
type: "bar",
barWidth: "20%",
},
],
});
HttpManager.getAllSongList().then((result) => {
songListCount.value = result.data.length;
for (let item of result.data) {
for (let i = 0; i < songStyle.xAxis.data.length; i++) {
if (item.style.includes(songStyle.xAxis.data[i])) {
songStyle.series[0].data[i]++;
}
}
}
// const songStyleChart = echarts.init(proxy.$refs.songStyle);
songStyleChart = echarts.init(document.getElementById("songStyle")!);
songStyleChart.setOption(songStyle);
});
//</editor-fold>
</script>
<style scoped>
.card-content {
display: flex;
align-items: center;
justify-content: space-around;
height: 100px;
padding-left: 20%;
text-align: center;
}
.card-left {
display: flex;
font-size: 3rem;
}
.card-right {
flex: 1;
font-size: 14px;
}
.card-num {
font-size: 30px;
font-weight: bold;
}
h3 {
margin: 10px 0;
text-align: center;
}
.cav-info {
border-radius: 6px;
overflow: hidden;
height: 250px;
background-color: white;
}
</style>
|
const mongoose = require('mongoose');
const Card = require('../models/card');
const { STATUS_CODES } = require('../utils/constants');
const RequestError = require('../errors/RequestError');
const NotFoundError = require('../errors/NotFoundError');
const ForbiddenError = require('../errors/ForbiddenError');
const createCard = (req, res, next) => {
const { name, link } = req.body;
Card.create({ name, link, owner: req.user._id })
.then((card) => res.status(STATUS_CODES.CREATED).send(card))
.catch((err) => {
if (err instanceof mongoose.Error.ValidationError) {
next(new RequestError('Переданы некорректные данные при создании карточки'));
return;
}
next(err);
});
};
const getCards = (req, res, next) => {
Card.find({}).sort({ createdAt: -1 })
.then((cards) => res.send(cards))
.catch(next);
};
const likeCard = (req, res, next) => {
Card.findByIdAndUpdate(req.params.cardId, { $addToSet: { likes: req.user._id } }, { new: true })
.orFail(new NotFoundError('Карточка с указанным id не найдена'))
.then((card) => res.send(card))
.catch((err) => {
if (err instanceof mongoose.Error.CastError) {
next(new RequestError('Переданы некорректные данные для постановки/снятии лайка'));
return;
}
next(err);
});
};
const dislikeCard = (req, res, next) => {
Card.findByIdAndUpdate(req.params.cardId, { $pull: { likes: req.user._id } }, { new: true })
.orFail(new NotFoundError('Карточка с указанным id не найдена'))
.then((card) => res.send(card))
.catch((err) => {
if (err instanceof mongoose.Error.CastError) {
next(new RequestError('Переданы некорректные данные для постановки/снятии лайка'));
return;
}
next(err);
});
};
const deleteCard = (req, res, next) => {
const { cardId } = req.params;
const { _id } = req.user;
Card.findById(cardId)
.orFail(new NotFoundError('Карточка с указанным id не найдена'))
.then((card) => {
if (_id !== card.owner.toString()) {
next(new ForbiddenError('У вас не достаточно прав для данной операции'));
return;
}
Card.deleteOne({ _id: card._id })
.then(() => res.send(card))
.catch((err) => {
if (err instanceof mongoose.Error.CastError) {
next(new RequestError('Переданы некорректные данные карточки'));
return;
}
next(err);
});
})
.catch((err) => {
if (err instanceof mongoose.Error.CastError) {
next(new RequestError('Переданы некорректные данные карточки'));
return;
}
next(err);
});
};
module.exports = {
createCard,
getCards,
deleteCard,
likeCard,
dislikeCard,
};
|
<template>
<v-card>
<link
rel="preload"
as="style"
type="text/css"
onload="this.rel = 'stylesheet'"
href="https://unpkg.com/katex@0.6.0/dist/katex.min.css"
/>
<v-toolbar dark color="primary">
<v-btn icon dark @click="close()" class="mr-2">
<v-icon>{{ mdiClose }}</v-icon>
</v-btn>
<h2>{{ $t('FAB.CREATE.new_question') }}</h2>
<v-spacer></v-spacer>
</v-toolbar>
<v-tooltip right v-if="e1 > 1">
<template v-slot:activator="{ on }">
<v-btn
color="grey lighten-3"
v-on="on"
dark
fab
fixed
bottom
left
@click="e1 = e1 - 1"
>
<v-icon color="blue">{{ mdiArrowLeft }}</v-icon>
</v-btn>
</template>
<span>{{ $t('QUESTIONS.EDIT.back') }}</span>
</v-tooltip>
<v-tooltip left v-if="e1 < 2">
<template v-slot:activator="{ on }">
<v-btn
color="blue"
class="mr-4"
v-on="on"
dark
fab
fixed
bottom
right
@click="e1 = 2"
>
<v-icon color="white">{{ mdiArrowRight }}</v-icon>
</v-btn>
</template>
<span>{{ $t('USERNAME_MODAL.TEXT.continue') }}</span>
</v-tooltip>
<v-tooltip left v-else>
<template v-slot:activator="{ on }">
<v-btn
color="blue"
class="mr-4"
v-on="on"
fab
fixed
bottom
right
:dark="formIsValid"
:disabled="!formIsValid"
:loading="loading || createLoading"
@click="onCreateQuestion()"
>
<v-icon color="white">{{ mdiContentSave }}</v-icon>
</v-btn>
</template>
<span>{{ $t('TEST.TEST_FORM.save') }}</span>
</v-tooltip>
<v-container fluid>
<v-row>
<v-col :cols="$vuetify.breakpoint.width <= 794 ? 12 : void 0">
<v-card>
<form @submit.prevent="onCreateQuestion">
<v-stepper alt-labels v-model="e1">
<v-stepper-header>
<v-stepper-step editable :complete="e1 > 1" step="1">
{{ $t('TEST.QUIZ.info') }}
</v-stepper-step>
<v-divider class="mx-2" style="margin-top: 50px"></v-divider>
<v-stepper-step editable step="2">
{{ $t('TEST.QUIZ.answers') }}
</v-stepper-step>
</v-stepper-header>
<v-stepper-items>
<v-stepper-content step="1">
<v-container>
<v-row class="pa-0 ma-0">
<v-col class="pa-0 ma-0">
<v-text-field
v-model="name"
dense
outlined
required
rounded
id="name"
name="name"
label="ID"
:rules="[
v => !!v || $t('QUESTIONS.FORM.required'),
v =>
v.length < 8 || $t('QUESTIONS.FORM.max-length'),
]"
></v-text-field>
</v-col>
</v-row>
<v-row class="pa-0 ma-0">
<v-col class="pa-0 ma-0">
<v-select
v-model="subject"
dense
flat
outlined
rounded
id="subject"
name="subject"
:label="$t('QUESTIONS.FORM.subject')"
:items="subjectItems.map(s => s.name)"
></v-select>
</v-col>
</v-row>
<v-row class="pa-0 ma-0">
<v-col class="pa-0 ma-0">
<v-select
v-model="level"
dense
flat
outlined
rounded
item-value="value"
item-text="label"
:label="$t('QUESTIONS.FORM.level')"
:items="
levels.map(l => ({
...l,
label: $t('TEST.LEVEL.' + l.value.name),
}))
"
></v-select>
</v-col>
</v-row>
<v-row justify="center" class="pa-0 ma-0">
<v-col cols="12" class="pa-0 ma-0">
<VueTextEditor
v-if="+e1 === 1"
outlined
:placeholder="$t('QUESTIONS.FORM.description')"
:groups="['format', 'align', 'list', 'format2']"
:value="questionDescription"
:height="300"
@textChange="questionDescription = $event"
/>
</v-col>
</v-row>
<v-row justify="center" class="pa-0 ma-0 mt-6">
<v-col cols="12" class="pa-0 ma-0">
<v-file-input
v-model="image"
clearable
dense
outlined
rounded
accept="image/*"
:label="$t('QUESTIONS.FORM.image')"
@change="checkImageType"
/>
</v-col>
</v-row>
<v-row v-if="image" justify="center" class="pa-0 ma-0">
<v-radio-group
v-model="imageSize"
row
class="pa-0 ma-0"
>
<v-radio label="1x" value="1x"></v-radio>
<v-radio label="2x" value="2x"></v-radio>
<v-radio label="3x" value="3x"></v-radio>
</v-radio-group>
</v-row>
</v-container>
</v-stepper-content>
<v-stepper-content step="2" class="pa-0 ma-0">
<v-container class="px-8 pb-8 pt-4 ma-0">
<v-row class="pa-0 ma-0 mb-2">
<v-checkbox
v-model="multipleAnswers"
:label="$t('QUESTIONS.FORM.multi_answers')"
></v-checkbox>
</v-row>
<v-row
v-for="(item, index) in answers"
:key="index"
class="pa-0 ma-0"
:class="{ 'pt-2': index > 0 }"
>
<v-checkbox
v-if="multipleAnswers"
v-model="selectedAnswers"
class="pa-0 pt-2 ma-0"
:value="item.ansId"
></v-checkbox>
<v-radio-group
v-else
v-model="radios"
class="pa-0 pt-2 ma-0"
>
<v-radio :value="item.ansId"></v-radio>
</v-radio-group>
<v-col class="pa-0 ma-0">
<v-text-field
v-model="item.text"
dense
outlined
rounded
class="pa-0 ma-0"
:placeholder="letters[index]"
></v-text-field>
<v-text-field
v-model="item.description"
dense
outlined
rounded
class="pa-0 ma-0"
style="margin-top: -12px !important"
:placeholder="$t('QUESTIONS.FORM.justification')"
></v-text-field>
</v-col>
</v-row>
<v-row
class="question-form__answer-justification pa-0 ma-0 mt-2"
>
<VueTextEditor
v-if="+e1 === 2"
outlined
:placeholder="
$t('QUESTIONS.FORM.general_justification')
"
:height="300"
:value="answerJustification"
:groups="['format', 'list', 'format2']"
@textChange="answerJustification = $event"
/>
</v-row>
<v-row class="pa-0 ma-0 mt-8">
<v-text-field
v-model="answerJustificationSource"
dense
outlined
rounded
class="pa-0 ma-0"
:label="$t('QUESTIONS.FORM.justification_source')"
></v-text-field>
</v-row>
</v-container>
</v-stepper-content>
</v-stepper-items>
</v-stepper>
</form>
</v-card>
</v-col>
<v-col :cols="$vuetify.breakpoint.width <= 600 ? 12 : void 0">
<Preview
:name="name"
:subject="subject"
:questionDesc="questionDescription"
:answers="answers"
:answerJustification="answerJustification"
:answerJustificationSource="answerJustificationSource"
:image="imagePreview"
/>
</v-col>
</v-row>
<v-snackbar
v-model="createErrorSnackBar"
light
color="red darken-2"
right
top
vertical
:timeout="15000"
>
<span style="color: white; font-size: 1rem">
{{ $t('QUESTIONS.FORM.id_in_use') }}
<br />
{{ $t('QUESTIONS.FORM.change_id') }}
</span>
<template v-slot:action="{ attrs }">
<v-btn
dark
color="white"
text
v-bind="attrs"
@click="createErrorSnackBar = false"
>
{{ $t('FAB.TEXT.close') }}
</v-btn>
</template>
</v-snackbar>
</v-container>
</v-card>
</template>
<script>
import {
mdiClose,
mdiPlus,
mdiMinus,
mdiArrowLeft,
mdiArrowRight,
mdiContentSave,
} from '@mdi/js'
import Preview from './Preview'
import VueTextEditor from '../Shared/VueTextEditor.vue'
export default {
name: 'QuestionForm',
components: {
Preview,
VueTextEditor,
},
props: ['questionRequest', 'page'],
data() {
return {
mdiClose,
mdiPlus,
mdiMinus,
mdiArrowLeft,
mdiArrowRight,
mdiContentSave,
createErrorSnackBar: false,
createLoading: false,
imagePreview: '',
image: null,
imagesAsURL: '',
imageSize: '1x',
questionDescription: '',
e1: 1,
test: null,
radios: '',
chips: [],
items: [],
letters: ['A', 'B', 'C', 'D'],
selectedAnswers: [],
multipleAnswers: false,
answers: [
{ text: '', description: '', ansId: 'radio-1', value: false },
{ text: '', description: '', ansId: 'radio-2', value: false },
{ text: '', description: '', ansId: 'radio-3', value: false },
{ text: '', description: '', ansId: 'radio-4', value: false },
],
answerJustification: '',
answerJustificationSource: '',
name: '',
subject: '',
level: {
index: 0,
name: 'beginner',
},
levels: [
{
value: {
index: 0,
name: 'beginner',
},
},
{
value: {
index: 1,
name: 'intermediary',
},
},
{
value: {
index: 2,
name: 'advanced',
},
},
{
value: {
index: 3,
name: 'expert',
},
},
],
}
},
computed: {
formIsValid() {
const name = (this.name ?? '').trim()
return (
!!name &&
name.length < 8 &&
!!this.subject &&
(this.multipleAnswers ? !!this.selectedAnswers.length : !!this.radios)
)
},
userClaims() {
return this.$store.getters.getUserClaims
},
userInfo() {
return this.$store.getters.userInfo
},
subjectItems() {
return this.$store.state.Subject.subjects
},
loading() {
return this.$store.getters.loading
},
},
watch: {
radios() {
this.setSingleAnswer()
},
selectedAnswers() {
this.setMultipleAnswers()
},
multipleAnswers(value) {
if (value) {
this.setMultipleAnswers()
return
}
this.setSingleAnswer()
},
name(value) {
this.name = value.trim().replace(/\s/g, '')
},
},
methods: {
updateData(variable) {
this.questionDescription = variable
},
setMultipleAnswers() {
this.answers.forEach(element => {
element.value = this.selectedAnswers.includes(element.ansId)
})
},
setSingleAnswer() {
this.answers.forEach(element => {
element.value = element.ansId === this.radios
})
},
async onCreateQuestion() {
this.createLoading = true
const exist = await this.$store.dispatch('questionExists', this.name)
if (exist) {
this.createLoading = false
this.createErrorSnackBar = true
return
}
let url = ''
if (this.image) {
const imageToUpload = { name: this.name, image: this.image }
url = await this.$store.dispatch('uploadImageQuestion', imageToUpload)
this.imagesAsURL = url
}
const questionData = {
name: this.name.toUpperCase(),
subject: this.subject,
level: this.level,
question: this.questionDescription,
multipleAnswers: this.multipleAnswers,
answers: this.answers,
answerJustification: this.answerJustification,
answerJustificationSource: this.answerJustificationSource,
image: url,
imageSize: this.imageSize,
}
if (this.userClaims && this.userClaims['admin']) {
await this.$store.dispatch('createQuestion', {
question: questionData,
page: this.page,
})
} else {
await this.$store.dispatch('createQuestionRequest', {
request: {
...questionData,
userId: this.userInfo.id,
status: '0-pendant',
},
})
await this.$store.dispatch('refetchRequests')
}
this.$emit('questionCreated')
this.createLoading = false
this.setInitialData()
this.close()
},
setInitialData() {
this.confirmTitle = false
this.questionDescription = ''
this.imageSize = '1x'
this.e1 = 1
this.test = null
this.level = {
index: 0,
name: 'beginner',
}
this.radios = ''
this.chips = []
this.items = []
this.selectedAnswers = []
this.multipleAnswers = false
this.answers = [
{ text: '', ansId: 'radio-1', value: false },
{ text: '', ansId: 'radio-2', value: false },
{ text: '', ansId: 'radio-3', value: false },
{ text: '', ansId: 'radio-4', value: false },
]
this.answerJustification = ''
this.answerJustificationSource = ''
this.name = ''
this.subject = ''
this.image = null
this.imagesAsBase64 = ''
},
checkImageType(file) {
if (file && file.type) {
if (!file.type.match(/image.*/)) {
this.$store.commit('setError', {
message: 'O arquivo inserido NÃO é uma imagem!',
})
this.image = null
} else if (file.size > 2000000) {
this.$store.commit('setError', {
message: 'O tamanho da imagem deve ser no MÁXIMO 2 MB!',
})
this.image = null
} else {
const reader = new FileReader()
reader.onload = readerEvent => {
this.imagePreview = readerEvent.target.result
}
reader.readAsDataURL(file)
}
} else if (this.imagePreview) {
this.imagePreview = ''
}
},
close() {
this.setInitialData()
this.$emit('closeDialogNew')
},
},
}
</script>
<style>
.answer-block {
margin: 0 !important;
}
.answer-block .col {
padding: 0 10px 0 10px !important;
}
.v-stepper__header {
box-shadow: 0 1px 0 0 #cfcfcf !important;
}
.v-text-editor__container {
border-radius: 28px;
}
.question-form__answer-justification .v-text-editor {
width: 100%;
}
</style>
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library fuchsia.lowpan.device;
using fuchsia.lowpan;
/// Protocol for returning the results of a network scan operation.
///
/// Closing the client end of an instance of this protocol will effectively
/// cancel the scan operation.
protocol BeaconInfoStream {
/// Called to fetch the next set of received beacons.
///
/// The last set will have zero items. Once all received
/// beacons have been returned, this channel will close.
Next() -> (vector<fuchsia.lowpan.BeaconInfo>:MAX_STREAM_SET_SIZE beacons);
};
/// Describes the parameters of a network scan.
table NetworkScanParameters {
/// Subset of channels to scan.
///
/// If unspecified, all channels will be scanned.
1: vector<ChannelIndex>:fuchsia.lowpan.MAX_CHANNELS channels;
/// Transmit power (in dBm to the antenna) for transmitting
/// beacon requests.
///
/// Note that hardware limitations may cause the actual
/// used transmit power to differ from what is specified.
/// In that case the used transmit power will always be
/// the highest available transmit power that is less than
/// the specified transmit power. If the desired transmit
/// power is lower than the lowest transmit power supported
/// by the hardware, then that will be used instead.
2: int32 tx_power_dbm;
};
|
import { OccupationalHealthcareEntry } from "../types";
import WorkIcon from "@mui/icons-material/Work";
const OccupationalEntry: React.FC<{
entry: OccupationalHealthcareEntry;
getDiagnosisText: (code: string) => string;
}> = ({
entry,
getDiagnosisText,
}: {
entry: OccupationalHealthcareEntry;
getDiagnosisText: (code: string) => string;
}) => {
return (
<div>
<p>
{entry.date}
<WorkIcon />
<i> {entry.employerName}</i>
</p>
<p>
<i>{entry.description}</i>
</p>
<ul>
{entry.diagnosisCodes ? (
Object.values(entry.diagnosisCodes).map((d: string) => (
<li key={d}>
{d} {getDiagnosisText(d)}
</li>
))
) : (
<></>
)}
</ul>
{entry.sickLeave ? (
<p>
sickleave from {entry.sickLeave.startDate} to{" "}
{entry.sickLeave.endDate}
</p>
) : (
<></>
)}
<p>diagnose by {entry.specialist}</p>
</div>
);
};
export default OccupationalEntry;
|
import os
import pymongo
from dotenv import load_dotenv
from flask import Flask, jsonify, request, render_template
from scrapers.singer import getSingerData
from scrapers.abans import getAbansData
from scrapers.damro import getDamroData
from scrapers.singhagiri import getSinghagiriData
from scrapers.softlogic import getSoftlogicData
from flask_apscheduler import APScheduler
from pymongo import MongoClient
from tasks import taskManager
import datetime
load_dotenv()
client = MongoClient(os.getenv('MONGO_URL'))
db = client['PricePal']
class Config:
SCHEDULER_API_ENABLED = True
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
# store server started time
initiateTime = datetime.datetime.now().isoformat()
print("now =", initiateTime)
reqCount = 0
def addReq():
global reqCount
reqCount += 1
@app.route('/', methods=['GET'])
def get_home():
activeCount = taskManager.getActiveTaskCount()
allCount = taskManager.getTaskCount()
serverStatus = "Running"
data = {
"allTasks":allCount,
"activeTasks":activeCount,
"status":serverStatus,
"req":reqCount
}
return render_template('home.html', initiateTime=initiateTime, data=data)
# Task Manager
@app.route('/listTasks', methods=['GET'])
def list_tasks():
data = taskManager.getTasks()
return render_template('listTask.html', data=data)
@app.delete('/listTasks/<int:id>')
def delete_task(id):
isDeleted = taskManager.deleteTask(id)
if isDeleted:
return jsonify({'message':'Task Deleted Successfully'}),200
else:
return jsonify({'message':'Task Not Found'}),404
@app.route('/addTask', methods=['GET','POST'])
def add_task():
if request.method == "GET":
return render_template('addTask.html')
else:
data = request.get_json()
url = data['url']
platform = data['platform']
category = data['category']
interval = data['interval']
isAdded = taskManager.addTask(url,platform,category,interval)
if isAdded:
return jsonify({'message':'Task Added Successfully'}),201
else:
return jsonify({'message':'Failed To Add Task'}),500
@app.route('/editTask/<int:id>', methods=['GET','POST'])
def edit_task(id):
if request.method == "GET":
data = taskManager.getTaskByID(id)
print(data)
return render_template('editTask.html', data=data)
else:
data = request.get_json()
url = data['url']
platform = data['platform']
category = data['category']
interval = data['interval']
status = data['status']
isAdded = taskManager.editTask(id,url,platform,category,interval,status)
if isAdded:
return jsonify({'message':'Task Updated Successfully'}),201
else:
return jsonify({'message':'Failed To Update Task'}),500
@app.put('/updateState/<int:id>/<string:state>')
def update_state(id,state):
isUpdated = taskManager.setState(id,state)
if isUpdated:
return jsonify({'message':'State Changed'}),200
else:
return jsonify({'message':'Failed to Change State'}),404
# API Mode
@app.route('/singer', methods=['GET'])
async def get_singer_data():
addReq()
url_param = request.args.get('url', None)
if url_param is not None:
data = getSingerData(url_param)
return data
else:
return "No URL parameter received."
@app.route('/abans', methods=['GET'])
async def get_abans_data():
addReq()
url_param = request.args.get('url', None)
if url_param is not None:
data = getAbansData(url_param)
return data
else:
return "No URL parameter received."
@app.route('/damro', methods=['GET'])
async def get_damro_data():
addReq()
url_param = request.args.get('url', None)
if url_param is not None:
data = getDamroData(url_param)
return data
else:
return "No URL parameter received."
@app.route('/singhagiri', methods=['GET'])
async def get_singhagiri_data():
addReq()
url_param = request.args.get('url', None)
if url_param is not None:
data = getSinghagiriData(url_param)
return data
else:
return "No URL parameter received."
@app.route('/softlogic', methods=['GET'])
async def get_softlogic_data():
addReq()
url_param = request.args.get('url', None)
if url_param is not None:
data = getSoftlogicData(url_param)
return data
else:
return "No URL parameter received."
# get dataset
def get_singer_data(url,category):
addReq()
data = getSingerData(url,category)
collection = db[category]
for ele in data:
p = collection.find_one({"title":ele["title"]})
if p is None:
id = collection.insert_one(ele).inserted_id
else:
q = collection.update_one({"title":p["title"]}, {"$set":ele}, upsert=False)
print(f"Singer {category.capitalize()} Scraped !")
def get_abans_data(url,category):
addReq()
data = getAbansData(url,category)
collection = db[category]
for ele in data:
p = collection.find_one({"title":ele["title"]})
if p is None:
id = collection.insert_one(ele).inserted_id
else:
q = collection.update_one({"title":p["title"]}, {"$set":ele}, upsert=False)
print(f"Abans {category.capitalize()} Scraped !")
def get_damro_data(url,category):
addReq()
data = getDamroData(url,category)
collection = db[category]
for ele in data:
p = collection.find_one({"title":ele["title"]})
if p is None:
id = collection.insert_one(ele).inserted_id
else:
q = collection.update_one({"title":p["title"]}, {"$set":ele}, upsert=False)
print(f"Damro {category.capitalize()} Scraped !")
def get_softlogic_data(url,category):
addReq()
data = getSoftlogicData(url,category)
collection = db[category]
for ele in data:
p = collection.find_one({"title":ele["title"]})
if p is None:
id = collection.insert_one(ele).inserted_id
else:
q = collection.update_one({"title":p["title"]}, {"$set":ele}, upsert=False)
print(f"Softlogic {category.capitalize()} Scraped !")
def get_singhagiri_data(url,category):
addReq()
data = getSinghagiriData(url,category)
collection = db[category]
for ele in data:
p = collection.find_one({"title":ele["title"]})
if p is None:
id = collection.insert_one(ele).inserted_id
else:
q = collection.update_one({"title":p["title"]}, {"$set":ele}, upsert=False)
print(f"Singhagiri {category.capitalize()} Scraped !")
# Reload tasks Route
@app.route('/reloadTasks',methods=['GET'])
def reload():
scheduler.remove_all_jobs()
tasks= taskManager.getActiveTasks()
print(tasks)
for task in tasks:
if task[2] == "singer":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_singer_data(url,category), trigger='interval', hours=task[4], max_instances=1)
elif task[2] == "abans":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_abans_data(url,category), trigger='interval', hours=task[4], max_instances=1)
elif task[2] == "damro":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_damro_data(url,category), trigger='interval', hours=task[4], max_instances=1)
elif task[2] == "singhagiri":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_singhagiri_data(url,category), trigger='interval', hours=task[4], max_instances=1)
elif task[2] == "softlogic":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_softlogic_data(url,category), trigger='interval', hours=task[4], max_instances=1)
else:
pass
return jsonify({'message':'reloaded'}),201
# Run task Scheduler on server startup
tasks= taskManager.getActiveTasks()
print(tasks)
for task in tasks:
if task[2] == "singer":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_singer_data(url,category), trigger='interval', hours=task[4], max_instances=1)
elif task[2] == "abans":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_abans_data(url,category), trigger='interval', hours=task[4], max_instances=1)
elif task[2] == "damro":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_damro_data(url,category), trigger='interval', hours=task[4], max_instances=1)
elif task[2] == "singhagiri":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_singhagiri_data(url,category), trigger='interval', hours=task[4], max_instances=1)
elif task[2] == "softlogic":
job_id = f"ScheduledScraping_{task[0]}"
scheduler.add_job(id=job_id, func=lambda url=task[1], category=task[3]: get_softlogic_data(url,category), trigger='interval', hours=task[4], max_instances=1)
else:
pass
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
|
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Logo from './logo';
import SearchBar from './search_bar';
import NavbarTabItem from './navbar_tab_item';
import NavbarCreateItem from './navbar_create_item';
import NavbarMessengerItem from './navbar_messenger_item';
import NavbarNotificationsItem from './navbar_notifications_item';
import NavbarSettingsItem from './navbar_settings_item';
import NavbarCreateMenu from './navbar_create_menu';
import NavbarMessengerMenu from './navbar_messenger_menu';
import NavbarNotificationsMenu from './navbar_notifications_menu';
import NavbarSettingsMenu from './navbar_settings_menu';
import OutsideClickNotifier from '../shared/outside_click_notifier';
import PostForm from '../shared/post_form';
import { CSSTransition } from 'react-transition-group';
const ItemType = {
CREATE: 'CREATE',
MESSENGER: 'MESSENGER',
NOTIFICATIONS: 'NOTIFICATIONS',
SETTINGS: 'SETTINGS'
}
const Navbar = ({
loggedIn,
logout,
currentUserId,
currentUser,
currentProfile,
fetchProfile,
createPost,
fetchUser,
profiles,
users,
fetchNewsfeed,
fetchUsers
}) => {
const [selected, setSelected] = useState('');
const [ showPostForm, setShowPostForm] = useState(false);
const onPostFormExit = () => {
setShowPostForm(false)
$('body').css({
'position': 'static'
})
}
useEffect(() => {
if (currentUserId) {
fetchProfile(currentUserId)
}
}, [])
const onSelect = (type) => {
return (e) => {
setSelected(type === selected ? '' : type);
}
}
return loggedIn ? (
<nav className='navbar-layout'>
<ul className='navbar-layout__search-section'>
<li className='navbar-layout__search-item'>
<Link to='/'>
<Logo />
</Link>
</li>
<li className='navbar__search-item'><SearchBar fetchUsers={fetchUsers} /></li>
</ul>
<ul className='navbar-layout__tabs-section'>
<li className='navbar-layout__tab-item'>
<NavbarTabItem
type='home'
path='/'
/>
</li>
<li className='navbar-layout__tab-item'>
<NavbarTabItem
type='friends'
path='/friends'
/>
</li>
</ul>
<ul className='navbar-layout__user-section'>
<li>
<NavbarCreateItem
id='navbar-create-item'
active={selected === ItemType.CREATE}
setSelected={onSelect(ItemType.CREATE)}
/>
{
selected === ItemType.CREATE ?
<OutsideClickNotifier excludeIds={['navbar-create-item']} sideEffect={() => { setSelected('') }}>
<NavbarCreateMenu setShowPostForm={setShowPostForm} setSelected={setSelected}/>
</OutsideClickNotifier>
: null
}
</li>
{/* <li>
<NavbarMessengerItem
id='navbar-messenger-item'
active={selected === ItemType.MESSENGER}
setSelected={onSelect(ItemType.MESSENGER)}
/>
{
selected === ItemType.MESSENGER ?
<OutsideClickNotifier excludeIds={['navbar-messenger-item']} sideEffect={() => { setSelected('') }}>
<NavbarMessengerMenu />
</OutsideClickNotifier>
: null}
</li>
<li>
<NavbarNotificationsItem
id='navbar-notifications-item'
active={selected === ItemType.NOTIFICATIONS}
setSelected={onSelect(ItemType.NOTIFICATIONS)} />
{
selected === ItemType.NOTIFICATIONS ?
<OutsideClickNotifier excludeIds={['navbar-notifications-item']} sideEffect={() => { setSelected('') }}>
<NavbarNotificationsMenu />
</OutsideClickNotifier>
: null
}
</li> */}
<li>
<NavbarSettingsItem
id='navbar-settings-item'
active={selected === ItemType.SETTINGS}
setSelected={onSelect(ItemType.SETTINGS)}
currentProfile={currentProfile}
/>
{
selected === ItemType.SETTINGS ?
<OutsideClickNotifier excludeIds={['navbar-settings-item']} sideEffect={() => { setSelected('') }}>
<NavbarSettingsMenu currentProfile={currentProfile} currentUser={currentUser} currentUserId={currentUserId} setSelected={setSelected} logout={logout} />
</OutsideClickNotifier>
: null
}
</li>
</ul>
<CSSTransition
in={showPostForm}
timeout={200}
classNames='js-show-modal'
unmountOnExit
onEnter={() => setShowPostForm(true)}
onExited={onPostFormExit}
>
<div className='splash-layout__modal'>
<div className='splash-layout__modal-top-guard'>
<div className='splash-layout__modal-center'>
<OutsideClickNotifier excludeIds={[]} sideEffect={() => setShowPostForm(false)}>
<PostForm
currentProfile={profiles[users[currentUserId].profileId]}
currentUser={users[currentUserId]}
setShowPostForm={setShowPostForm}
createPost={createPost}
fetchUser={fetchUser}
fetchNewsfeed={fetchNewsfeed}
/>
</OutsideClickNotifier>
</div>
</div>
<div className='splash-layout__modal-background'></div>
</div>
</CSSTransition>
</nav>
) : null;
}
export default Navbar;
|
// Countdown setup using moment-timezone
const endDate1 = moment.tz("2025-01-19 23:59:59", "America/New_York").valueOf();
const endDate2 = moment.tz("2025-04-19 23:59:59", "America/New_York").valueOf();
function updateCountdown1() {
const now = moment().tz("America/New_York").valueOf();
const distance = endDate1 - now;
if (distance < 0) {
document.getElementById('countdownBox1').innerHTML = "• The first countdown has ended — the initial deadline has passed •";
document.getElementById('welcomeMessage').innerHTML = "TikTok ban in progress?";
document.getElementById('timerRow2').style.display = 'none';
document.getElementById('extensionLabel').innerHTML = "Extension timer is running";
} else {
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById('countdown1').innerHTML = (days < 10 ? "0" : "") + days + "d " + (hours < 10 ? "0" : "") + hours + "h " + (minutes < 10 ? "0" : "") + minutes + "m " + (seconds < 10 ? "0" : "") + seconds + "s ";
}
}
function updateCountdown2() {
const now = moment().tz("America/New_York").valueOf();
const distance = endDate2 - now;
if (distance < 0) {
document.getElementById('countdownBox2').innerHTML = "• The extension deadline has also passed. TikTok may now be banned, depending on a sale •";
document.getElementById('welcomeMessage').innerHTML = "TikTok ban now in effect?";
} else {
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById('countdown2').innerHTML = (days < 10 ? "0" : "") + days + "d " + (hours < 10 ? "0" : "") + hours + "h " + (minutes < 10 ? "0" : "") + minutes + "m " + (seconds < 10 ? "0" : "") + seconds + "s ";
}
}
function initializeCountdowns() {
const now = moment().tz("America/New_York").valueOf();
if (endDate1 - now < 0) {
document.getElementById('countdownBox1').innerHTML = "• The first countdown has ended — the initial deadline has passed •";
document.getElementById('welcomeMessage').innerHTML = "TikTok ban in progress?";
document.getElementById('timerRow2').style.display = 'none';
document.getElementById('extensionLabel').innerHTML = "Extension timer is running";
} else {
setInterval(updateCountdown1, 1000);
}
if (endDate2 - now < 0) {
document.getElementById('countdownBox2').innerHTML = "• The extension deadline has also passed. TikTok may now be banned, depending on a sale •";
document.getElementById('welcomeMessage').innerHTML = "TikTok ban now in effect?";
} else {
setInterval(updateCountdown2, 1000);
}
}
initializeCountdowns();
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
}
function sharePage() {
if (navigator.share) {
navigator.share({
title: 'TikTok Ban Countdown',
url: window.location.href
}).then(() => {
console.log('Thanks for sharing!');
}).catch((err) => {
console.log(`Couldn't share because of`, err.message);
});
} else {
alert('Your browser does not support the Web Share API');
}
}
function shareOnFacebook() {
const url = encodeURIComponent(window.location.href);
const shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}`;
window.open(shareUrl, '_blank');
}
function shareOnTwitterX() {
const url = encodeURIComponent(window.location.href);
const shareUrl = `https://twitter.com/intent/tweet?url=${url}&text=Check%20out%20this%20TikTok%20ban%20countdown!`;
window.open(shareUrl, '_blank');
}
function shareOnLinkedIn() {
const url = encodeURIComponent(window.location.href);
const shareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${url}`;
window.open(shareUrl, '_blank');
}
function toggleContent(contentId, button) {
const contentElements = document.querySelectorAll('.content');
const buttons = document.querySelectorAll('.learn-more-button');
contentElements.forEach(content => {
if (content.id !== contentId) {
content.style.display = 'none';
}
});
buttons.forEach(btn => {
if (btn !== button) {
btn.classList.remove('active');
}
});
const content = document.getElementById(contentId);
if (content.style.display === 'block') {
content.style.display = 'none';
button.classList.remove('active');
} else {
content.style.display = 'block';
button.classList.add('active');
if (contentId === 'embedCode') {
document.getElementById('updateSelectionButton').style.display = 'inline-block';
}
}
}
function copyToClipboard() {
const code = document.querySelector('#embedCodeContent').textContent;
navigator.clipboard.writeText(code).then(() => {
alert('Code copied to clipboard!');
}).catch(err => {
alert('Failed to copy code: ' + err);
});
}
function showCustomizationOptions() {
document.getElementById('customizationOptions').style.display = 'block';
}
function generateCustomEmbedCode() {
const showDays = document.getElementById('showDays').checked;
const showHours = document.getElementById('showHours').checked;
const showMinutes = document.getElementById('showMinutes').checked;
const showSeconds = document.getElementById('showSeconds').checked;
const darkTheme = document.getElementById('darkTheme').checked;
const endMessage = document.getElementById('endMessage').value || '• The countdown has ended — the deadline has passed •';
const fontSize = document.getElementById('fontSize').value || '36';
const customCode = `<!-- TikTok Ban Countdown Embed Code -->
<div id="countdown-box" style="font-size: ${fontSize}px; ${darkTheme ? 'background-color: #2C2C2C; color: #FFFFFF;' : ''}">
<div class="timer-row">
<div class="countdown-label">In:</div>
<div class="countdown" id="countdown-embed">00d 00h 00m 00s</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.34/moment-timezone-with-data.min.js"></script>
<script>
var endDateEmbed = moment.tz("2025-01-19 23:59:59", "America/New_York").valueOf();
function updateCountdownEmbed() {
var now = moment().tz("America/New_York").valueOf();
var distance = endDateEmbed - now;
if (distance < 0) {
document.getElementById("countdown-box").innerHTML = "${endMessage}";
} else {
var days = ${showDays ? "Math.floor(distance / (1000 * 60 * 60 * 24)) + 'd '" : ""};
var hours = ${showHours ? "Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + 'h '" : ""};
var minutes = ${showMinutes ? "Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + 'm '" : ""};
var seconds = ${showSeconds ? "Math.floor((distance % (1000 * 60)) / 1000) + 's '" : ""};
document.getElementById("countdown-embed").innerHTML = (days < 10 ? "0" : "") + days + (hours < 10 ? "0" : "") + hours + (minutes < 10 ? "0" : "") + minutes + (seconds < 10 ? "0" : "") + seconds;
}
}
setInterval(updateCountdownEmbed, 1000);
</script>`;
document.getElementById('embedCodeContent').innerHTML = customCode;
document.getElementById('customizationOptions').style.display = 'none';
document.getElementById('updateSelectionButton').style.display = 'none';
}
document.getElementById('nightModeToggle').addEventListener('click', function() {
document.body.classList.toggle('dark-mode');
});
|
import Link, { LinkProps } from 'next/link';
import type { FunctionComponent } from 'react';
import { Stack } from 'components/layouts/Stack';
import { useClassNames } from 'hooks/useClassNames';
import type { StackProps } from 'types';
import { linkStackClassName } from './linkStack.css';
type LinkStackProps = (StackProps & LinkProps) | StackProps;
/**
* Allows all properties of both `Link` and `Stack`. Helpful when showing
* different pieces of info together, that conditionally has a URL associated
* with it. One example of this is the People section on the Episode page.
*/
export const LinkStack: FunctionComponent<LinkStackProps> = ({
children,
className,
...props
}) => {
const baseClassName = useClassNames(linkStackClassName, className);
return 'href' in props ? (
<Stack as={Link} className={baseClassName} {...props}>
{children}
</Stack>
) : (
<Stack className={baseClassName} {...props}>
{children}
</Stack>
);
};
|
//
// AppDelegate.swift
// Culinary
//
// Created by Sergey Nazarov on 01.12.2019.
// Copyright © 2019 Sergey Nazarov. All rights reserved.
//
import UIKit
import CoreData
import Moya
import RxSwift
import YandexMapKit
import VK_ios_sdk
import FBSDKCoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var authService: AuthService!
private let MAPKIT_API_KEY = "3b4cf0bf-f82b-48ca-9768-a07f8c284e91"
//если значение true не показываем алерт с информацие цен
//до следующего перезапуска приложения
var didShowCatMenu = false
var didShowAlertFeedback = false
//MARK:- Providers
let providerAuthServerAPI = MoyaProvider<AuthServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: false)])
let providerMenuSectionsServerAPI = MoyaProvider<MenuServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: true)])
let providerFeedbackServerAPI = MoyaProvider<FeedbackServerAPI>(manager: DownloadAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: true, cURL: true)])
let providerFiltersServerAPI = MoyaProvider<FiltersServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: false, cURL: false)])
let providerWishlistServerAPI = MoyaProvider<WishlistServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: false)])
let providerInfoUserServerAPI = MoyaProvider<InfoUserServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: true, cURL: true)])
let providerCafeServerAPI = MoyaProvider<CageServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: true, cURL: true)])
let providerContactsServerAPI = MoyaProvider<ContactsServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: true)])
let providerBasketServerAPI = MoyaProvider<BasketServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: true, cURL: true)])
let providerHistoryServerAPI = MoyaProvider<HistoryServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: true, cURL: true)])
let providerStocksServerAPI = MoyaProvider<StocksServerAPI>(manager: DefaultAlamofireManager.sharedManager,
plugins: [NetworkLoggerPlugin(verbose: true, cURL: true)])
let disposeBag = DisposeBag()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
YMKMapKit.setApiKey(MAPKIT_API_KEY)
self.authService = AuthService()
//MARK:- Facebook SignIn
ApplicationDelegate.shared.application( application, didFinishLaunchingWithOptions: launchOptions )
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// let vk = VKSdk.processOpen(url, fromApplication: UIApplication.OpenURLOptionsKey.sourceApplication.rawValue)
// let fb = ApplicationDelegate.shared.application( app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation] )
return false
}
// MARK: UISceneSession Lifecycle
@available(iOS 13.0, *)
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
@available(iOS 13.0, *)
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Culinary")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
-> A strong analysis depends on the integrity of the data. If the data you're using is compromised in any way, your analysis won't be as strong as it should be.
-> Data integrity is the accuracy, completeness, consistency, and trustworthiness of data throughout its lifecycle.
-> When data integrity is low, it can cause anything from the loss of a single pixel in an image to an incorrect medical decision. In some cases, one missing piece
can make all of your data useless.
-> Data integrity can be compromised in lots of different ways. There's a chance data can be compromised every time it's replicated, transferred, or manipulated in
any way.
-> Data replication is the process of storing data in multiple locations. If you're replicating data at different times in different places, there's a chance your
data will be out of sync. This data lacks integrity because different people might not be using the same data for their findings, which can cause inconsistencies.
-> There's also the issue of data transfer, which is the process of copying data from a storage device to memory, or from one computer to another. If your data
transfer is interrupted, you might end up with an incomplete data set, which might not be useful for your needs.
-> The data manipulation process involves changing the data to make it more organized and easier to read. Data manipulation is meant to make the data analysis process
more efficient, but an error during the process can compromise the efficiency. Finally, data can also be compromised through human error, viruses, malware, hacking,
and system failures, which can all lead to even more headaches.
-> 1. Data replication compromising data integrity: Continuing with the example, imagine you ask your international counterparts to verify dates and stick to one
format. One analyst copies a large dataset to check the dates. But because of memory issues, only part of the dataset is actually copied. The analyst would be
verifying and standardizing incomplete data. That partial dataset would be certified as compliant but the full dataset would still contain dates that weren't
verified. Two versions of a dataset can introduce inconsistent results. A final audit of results would be essential to reveal what happened and correct all
dates.
2. Data transfer compromising data integrity: Another analyst checks the dates in a spreadsheet and chooses to import the validated and standardized data back to
the database. But suppose the date field from the spreadsheet was incorrectly classified as a text field during the data import (transfer) process. Now some of
the dates in the database are stored as text strings. At this point, the data needs to be cleaned to restore its integrity.
3. Data manipulation compromising data integrity: When checking dates, another analyst notices what appears to be a duplicate record in the database and removes
it. But it turns out that the analyst removed a unique record for a company’s subsidiary and not a duplicate record for the company. Your dataset is now missing
data and the data must be restored for completeness.
-> 1. Data type
Values must be of a certain type: date, number, percentage, Boolean, etc.
If the data type is a date, a single number like 30 would fail the constraint and be invalid.
2. Data range
Values must fall between predefined maximum and minimum values
If the data range is 10-20, a value of 30 would fail the constraint and be invalid
3. Mandatory
Values can’t be left blank or empty
If age is mandatory, that value must be filled in
4. Unique
Values can’t have a duplicate
Two people can’t have the same mobile phone number within the same service area
5. Regular expression (regex) patterns
Values must match a prescribed pattern
A phone number must match ###-###-#### (no other characters allowed)
6. Cross-field validation
Certain conditions for multiple fields must be satisfied
Values are percentages and values from multiple fields must add up to 100%
7. Primary-key
(Databases only) value must be unique per column
A database table can’t have two rows with the same primary key value. A primary key is an identifier in a database that references a column in which each
value is unique. More information about primary and foreign keys is provided later in the program.
8. Set-membership
(Databases only) values for a column must come from a set of discrete values
Value for a column must be set to Yes, No, or Not Applicable
9. Foreign-key
(Databases only) values for a column must be unique values coming from a column in another table
In a U.S. taxpayer database, the State column must be a valid state or territory with the set of acceptable values defined in a separate States table
10. Accuracy
The degree to which the data conforms to the actual entity being measured or described
If values for zip codes are validated by street location, the accuracy of the data goes up.
11. Completeness
The degree to which the data contains all desired components or measures
If data for personal profiles required hair and eye color, and both are collected, the data is complete.
12. Consistency
The degree to which the data is repeatable from different points of entry or collection
If a customer has the same address in the sales and repair databases, the data is consistent.
-> Clean data + alignment to business objective = accurate conclusions
-> TYPES OF INSUFFICIENT DATA:
1. Data from only one source
2. Data that keeps updating
3. Outdated data
4. Geographically limited data
-> WAYS TO ADDRESS INSUFFICIENT DATA:
1. Identify trends with the available data
2. Wait for more data if time allows
3. Talk with stakeholders and adjust your objective
4. Look for a new dataset
-> A population is all possible data values in a certain dataset.
-> SAMPLE SIZE: a part of a population that's representative of the population. The goal is to get enough information from a small group within a population to
make predictions or conclusions about the whole population. The sample size helps ensure the degree to which you can be confident that your conclusions
accurately represent the population.
-> Sampling bias is when a sample isn't representative of the population as a whole. This means some members of the population are being overrepresented or
underrepresented.
-> Random sampling is a way of selecting a sample from a population so that every possible type of the sample has an equal chance of being chosen.
-> 1. Population
The entire group that you are interested in for your study. For example, if you are surveying people in your company, the population would be all the
employees in your company.
2. Sample
A subset of your population. Just like a food sample, it is called a sample because it is only a taste. So if your company is too large to survey every
individual, you can survey a representative sample of your population.
3. Margin of error
Since a sample is used to represent a population, the sample’s results are expected to differ from what the result would have been if you had surveyed the
entire population. This difference is called the margin of error. The smaller the margin of error, the closer the results of the sample are to what the
result would have been if you had surveyed the entire population.
4. Confidence level
How confident you are in the survey results. For example, a 95% confidence level means that if you were to run the same survey 100 times, you would get
similar results 95 of those 100 times. Confidence level is targeted before you start your study because it will affect how big your margin of error is at
the end of your study.
5. Confidence interval
The range of possible values that the population’s result would be at the confidence level of the study. This range is the sample result +/- the margin of
error.
6. Statistical significance
The determination of whether your result could be due to random chance or not. The greater the significance, the less due to chance.
-> Increase the sample size to meet specific needs of your project:
1. For a higher confidence level, use a larger sample size
2. To decrease the margin of error, use a larger sample size
3. For greater statistical significance, use a larger sample size
-> Statistical power is the probability of getting meaningful results from a test.
-> Hypothesis testing is a way to see if a survey or experiment has meaningful results.
-> If a test is statistically significant, it means the results of the test are real and not an error caused by random chance.
-> Which statistical power is typically considered the minimum for statistical significance? 0.8 or 80%
-> Statistical power can be calculated and reported for a completed experiment to comment on the confidence one might have in the conclusions drawn from the
results of the study. It can also be used as a tool to estimate the number of observations or sample size required in order to detect an effect in an experiment.
-> The confidence level is the probability that your sample accurately reflects the greater population. You can think of it the same way as confidence in anything
else. It's how strongly you feel that you can rely on something or someone. Having a 99 percent confidence level is ideal. But most industries hope for at least
a 90 or 95 percent confidence level.
-> A sample size calculator tells you how many people you need to interview (or things you need to test) to get results that represent the target population. Let’s review some terms you will come across when using a sample size calculator:
1. Confidence level: The probability that your sample size accurately reflects the greater population.
2. Margin of error: The maximum amount that the sample results are expected to differ from those of the actual population.
3. Population: This is the total number you hope to pull your sample from.
4. Sample: A part of a population that is representative of the population.
5. Estimated response rate: If you are running a survey of individuals, this is the percentage of people you expect will complete your survey out of those
who received the survey.
-> Margin of error is the maximum that the sample results are expected to differ from those of the actual population.
-> To calculate margin of error, you need three things: population size, sample size, and confidence level.
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="bootstrap-5.2.3-dist/css/bootstrap.css">
<link rel="stylesheet" href="css/site.css">
<!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> -->
<!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> -->
<style>
</style>
</head>
<body>
<!-- 콜랩스 -->
<p>
<a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
Link with href
</a>
<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-bs-target
</button>
</p>
<div class="collapse" id="collapseExample">
<div class="card card-body">
Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger.
</div>
</div>
<hr>
<!-- 수평콜랩스 -->
<p>
<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWidthExample" aria-expanded="false" aria-controls="collapseWidthExample">
Toggle width collapse
</button>
</p>
<div style="min-height: 120px;">
<div class="collapse collapse-horizontal" id="collapseWidthExample">
<div class="card card-body" style="width: 300px;">
This is some placeholder content for a horizontal collapse. It's hidden by default and shown when triggered.
</div>
</div>
</div>
<hr>
<!-- 다중항목 -->
<p>
<a class="btn btn-primary" data-bs-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Toggle first element</a>
<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button>
</p>
<div class="row">
<div class="col">
<div class="collapse multi-collapse" id="multiCollapseExample1">
<div class="card card-body">
Some placeholder content for the first collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
</div>
</div>
</div>
<div class="col">
<div class="collapse multi-collapse" id="multiCollapseExample2">
<div class="card card-body">
Some placeholder content for the second collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> -->
<!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script> -->
<!-- <script src="https://code.jquery.com/jquery-3.6.3.js"
integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script> -->
<script type="text/javascript" src="bootstrap-5.2.3-dist/js/bootstrap.bundle.js"></script>
</body>
</html>
|
#include "dog.h"
#include <stdlib.h>
/**
* new_dog - creates new dog
*
* @name: name of the dog
* @age: age of the dog
* @owner: name of the dog owner
*
* Return: pointer to new dog.
*/
dog_t *new_dog(char *name, float age, char *owner)
{
dog_t *dog;
int i = 0, j = 0, k;
if (!name || !owner)
return (NULL);
dog = malloc(sizeof(dog_t));
if (!dog)
return (NULL);
while (name[i])
i++;
dog->name = malloc(sizeof(char) * i + 1);
if (!dog->name)
{
free(dog);
return (NULL);
}
for (k = 0; k <= i; k++)
dog->name[k] = name[k];
while (owner[j])
j++;
dog->owner = malloc(sizeof(char) * j + 1);
if (!dog->owner)
{
free(dog->name);
free(dog);
return (NULL);
}
for (k = 0; k <= j; k++)
dog->owner[k] = owner[k];
dog->age = age;
return (dog);
}
|
import { useState, useEffect } from "react";
import { useRouter } from "next/router";
import Modal from "react-modal";
import styles from "../../styles/Video.module.css";
import { getYoutubeVideoById } from "../../lib/videos";
import { NavBar } from "../../components/nav/navbar";
import Like from "../../components/icons/like-icon";
import clsx from "classnames";
import DisLike from "../../components/icons/dislike-icon";
Modal.setAppElement("#__next");
export async function getStaticProps(context) {
const videoId = context.params.videoId;
const videoArray = await getYoutubeVideoById(videoId);
return {
props: {
video: videoArray.length > 0 ? videoArray[0] : {},
},
revalidate: 10, // In seconds
};
}
export async function getStaticPaths() {
const listOfVideos = ["bKh2G73gCCs", "OCsIlOuThuA"];
const paths = listOfVideos.map((videoId) => ({
params: { videoId },
}));
return { paths, fallback: "blocking" };
}
const Video = ({ video }) => {
const router = useRouter();
const videoId = router.query.videoId;
const [toggleLike, setToggleLike] = useState(false);
const [toggleDisLike, setToggleDisLike] = useState(false);
const {
title,
publishTime,
description,
channelTitle,
statistics: { viewCount } = { viewCount: 0 },
} = video;
useEffect(() => {
async function fetchData() {
const response = await fetch(`/api/stats?videoId=${videoId}`, {
method: "GET",
});
return response.json();
}
fetchData().then((data) => {
if (data.length > 0) {
const favourited = data[0].favourited;
if (favourited === 1) {
setToggleLike(true);
} else if (favourited === 0) {
setToggleDisLike(true);
}
}
});
}, [videoId]);
const runRatingService = async (favourited) => {
return await fetch("/api/stats", {
method: "POST",
body: JSON.stringify({
videoId,
favourited,
}),
headers: {
"Content-Type": "application/json",
},
});
};
const handleToggleDislike = async (e) => {
const val = !toggleDisLike;
setToggleDisLike(val);
setToggleLike(toggleDisLike);
const favourited = val ? 0 : 1;
await runRatingService(favourited);
};
const handleToggleLike = async (e) => {
const val = !toggleLike;
setToggleLike(val);
setToggleDisLike(toggleLike);
const favourited = val ? 1 : 0;
const response = await runRatingService(favourited);
console.log(response);
};
return (
<div className={styles.container}>
<NavBar />
<Modal
isOpen={true}
contentLabel="Watch the Video"
onRequestClose={() => {
router.back();
}}
className={styles.modal}
overlayClassName={styles.overlay}
>
<iframe
id="player"
className={styles.videoPlayer}
type="text/html"
width="100%"
height="390"
src={`http://www.youtube.com/embed/${videoId}?enablejsapi=1&origin=http://example.com&controls=0&rel=0`}
frameBorder="0"
></iframe>
<div className={styles.likeDislikeBtnWrapper}>
<div className={styles.likeBtnWrapper}>
<button onClick={handleToggleLike}>
<div className={styles.btnWrapper}>
<Like selected={toggleLike} />
</div>
</button>
</div>
<div className={styles.dislikeBtnWrapper}>
<button onClick={handleToggleDislike}>
<div className={styles.btnWrapper}>
<DisLike selected={toggleDisLike} />
</div>
</button>
</div>
</div>
<div className={styles.modalBody}>
<div className={styles.modalBodyContent}>
<div className={styles.col1}>
<p className={styles.publishTime}>{publishTime}</p>
<p className={styles.title}>{title}</p>
<p className={styles.description}>{description}</p>
</div>
<div className={styles.col2}>
<p className={clsx(styles.subText, styles.subTextWrapper)}>
<span className={styles.textColor}>Cast: </span>
<span className={styles.channelTitle}>{channelTitle}</span>
</p>
<p className={clsx(styles.subText, styles.subTextWrapper)}>
<span className={styles.textColor}>View Count: </span>
<span className={styles.channelTitle}>{viewCount}</span>
</p>
</div>
</div>
</div>
</Modal>
</div>
);
};
export default Video;
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TimesheetDataTableComponent } from './timesheet-data-table.component';
import { TimesheetModule } from '@features/timesheet/timesheet.module';
import { TestBaseModule, mockTimesheet, mockTimesheet2 } from 'src/app/spec/data-service-test.spec';
import { DraftRowInit, DraftRowId } from '@features/timesheet/constants';
import { FormGroup, FormControl, Validators } from '@angular/forms';
describe('TimesheetDataTableComponent', () => {
let component: TimesheetDataTableComponent;
let fixture: ComponentFixture<TimesheetDataTableComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
TestBaseModule,
TimesheetModule
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TimesheetDataTableComponent);
component = fixture.componentInstance;
component.dataSource = [mockTimesheet, mockTimesheet2];
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('createDraft', () => {
it('should call addDraftRow when there is value', () => {
const spy = spyOn(component, 'addDraftRow').and.callThrough();
component.createDraft = true;
expect(spy).toHaveBeenCalledTimes(1);
});
it('should NOT call addDraftRow when there is NO value', () => {
const spy = spyOn(component, 'addDraftRow').and.callThrough();
component.createDraft = null;
expect(spy).toHaveBeenCalledTimes(0);
});
});
describe('addDraftRow', () => {
it('should emit next focus true when draft is present', () => {
const spy = spyOn(component.focus$, 'next').and.callThrough();
component.draftRow = DraftRowInit;
component.addDraftRow();
expect(spy).toHaveBeenCalledWith(true);
});
it('should not call initForm when draft is present', () => {
const spy = spyOn(component, 'initForm').and.callThrough();
component.draftRow = DraftRowInit;
component.addDraftRow();
expect(spy).toHaveBeenCalledTimes(0);
});
it('should set draft row to init constant when draftRow is null', () => {
component.addDraftRow();
expect(component.draftRow).toEqual(DraftRowInit);
});
it('should add draftRow to top of datasource when draftRow is null', () => {
component.addDraftRow();
expect(component.dataSource[0]).toEqual(DraftRowInit);
});
it('should call formInit when draftRow is null', () => {
const spy = spyOn(component, 'initForm').and.callThrough();
component.addDraftRow();
expect(spy).toHaveBeenCalledTimes(1);
});
});
describe('edit', () => {
it('should call cancel', () => {
const spy = spyOn(component, 'cancel').and.callThrough();
component.edit(mockTimesheet);
expect(spy).toHaveBeenCalledTimes(1);
});
it('should call initForm with timesheet', () => {
const spy = spyOn(component, 'initForm').and.callThrough();
component.edit(mockTimesheet);
expect(spy).toHaveBeenCalledWith(mockTimesheet);
});
it('should set timesheet isEditing', () => {
component.edit(mockTimesheet);
expect(component.dataSource.find(d => d.id === mockTimesheet.id).isEditing).toEqual(true);
});
});
describe('toggleSelected', () => {
it('should set isSelected to true', () => {
component.toggleSelected(mockTimesheet);
expect(component.dataSource.find(d => d.id === mockTimesheet.id).isSelected).toEqual(true);
});
it('should set isSelected to false when called twice', () => {
component.toggleSelected(mockTimesheet);
component.toggleSelected(mockTimesheet);
expect(component.dataSource.find(d => d.id === mockTimesheet.id).isSelected).toEqual(false);
});
it('should emit selectedEntries', () => {
const spy = spyOn(component.selectedEntries, 'emit').and.callThrough();
component.toggleSelected(mockTimesheet);
expect(spy).toHaveBeenCalledWith(component.dataSource.filter(data => data.isSelected === true));
});
});
describe('cancel', () => {
it('should remove draft row from datasource if draftRow is not null', () => {
component.addDraftRow();
component.cancel();
expect(component.dataSource).not.toContain(DraftRowInit);
});
it('should set draftRow to null if draftRow is not null', () => {
component.addDraftRow();
component.cancel();
expect(component.draftRow).toBeFalsy();
});
it('should set isEditing to false on existing row', () => {
component.edit(mockTimesheet);
component.cancel();
expect(component.dataSource.filter(d => d.isEditing === true)).toEqual([]);
});
});
describe('save', () => {
it('should emit update when form is valid and no draftRow', () => {
const spy = spyOn(component.update, 'emit').and.callThrough();
component.edit(mockTimesheet);
component.draftRow = null;
component.formData.updateValueAndValidity();
component.save();
expect(spy).toHaveBeenCalledTimes(1);
});
it('should emit add when form is valid and draftRow is not null', () => {
const spy = spyOn(component.add, 'emit').and.callThrough();
component.addDraftRow();
component.formData.patchValue({title: 'test', type: 'test'});
component.formData.updateValueAndValidity();
component.save();
expect(spy).toHaveBeenCalledTimes(1);
});
it('should not emit when form is invalid', () => {
const addSpy = spyOn(component.add, 'emit').and.callThrough();
const updateSpy = spyOn(component.update, 'emit').and.callThrough();
component.addDraftRow();
component.formData.updateValueAndValidity();
component.save();
expect(addSpy).toHaveBeenCalledTimes(0);
expect(updateSpy).toHaveBeenCalledTimes(0);
});
});
describe('deleteTimesheet', () => {
it('should emit delete', () => {
const spy = spyOn(component.delete, 'emit').and.callThrough();
component.deleteTimesheet(mockTimesheet);
expect(spy).toHaveBeenCalledTimes(1);
});
});
describe('formDataToTimesheet', () => {
it('should return formdata as timesheet', () => {
component.initForm(mockTimesheet);
const result = component.formDataToTimesheet();
expect(result).toEqual(mockTimesheet);
});
it('should return timesheet id if not draft row', () => {
component.initForm(mockTimesheet);
const result = component.formDataToTimesheet();
expect(result.id).toEqual(mockTimesheet.id);
});
it('should return create timesheet id if draftRow not empty', () => {
component.addDraftRow();
const result = component.formDataToTimesheet();
expect(result.id).not.toEqual(DraftRowId);
});
});
});
|
def axes(self, axes):
'''Set the axes for this object's degrees of freedom.
Parameters
----------
axes : list of axis parameters
A list of axis values to set. This list must have the same number of
elements as the degrees of freedom of the underlying ODE object.
Each element can be
(a) None, which has no effect on the corresponding axis, or
(b) three floats specifying the axis to set, or
(c) a dictionary with an "axis" key specifying the axis to set and
an optional "rel" key (defaults to 0) specifying the relative
body to set the axis on.
'''
assert len(axes) == self.ADOF
for i, ax in enumerate(axes):
if ax is None:
continue
if not isinstance(ax, dict):
ax = dict(axis=ax)
self.ode_obj.setAxis(i, ax.get('rel', 0), ax['axis'])
|
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Faker\Factory;
use Illuminate\Database\Query\Builder;
class GamesSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$faker = Factory::create();
DB::table('games')->truncate(); //usuwa i resetuje id
/*
for ($i=0; $i < 100; $i++) {
DB::table('games')->insert([
'title' => $faker->words($faker->numberBetween(1, 3),true),
'description' => $faker->sentence(),
'publisher' => $faker->randomElement(['Atari','Activision','Blizzard','Interplay'],null),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'genre_id' => $faker->numberBetween(1, 6)
]);
} */
$games=[];
for ($i=0; $i < 50; $i++) {
$games[] =
[
'title' => $faker->words($faker->numberBetween(1, 3),true),
'description' => $faker->sentence(),
'publisher' => $faker->randomElement(['Atari','Activision','Blizzard','Interplay'],null),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'genre_id' => $faker->numberBetween(1, 6),
'score' => $faker->numberBetween(1, 100)
];
}
DB::table('games')->insert($games);
}
}
|
// Importing React, useEffect, and useState from React library
import React, { useEffect, useState } from "react";
// Importing Button and Modal components from react-daisyui
import { Button, Modal } from "react-daisyui";
// Importing social media share buttons and icons from react-share
import {
FacebookShareButton,
LinkedinShareButton,
TwitterShareButton,
WhatsappShareButton,
EmailShareButton,
} from 'react-share';
// Importing icons from various libraries
import { TbCopy } from "react-icons/tb";
import { IoMdClose } from "react-icons/io";
import { BsShare } from "react-icons/bs";
// Importing local image assets
import Whatsapp from "../../../Assets/whatsapp-icon.svg";
import Facebook from "../../../Assets/facebook-icon.svg";
import Twitter from "../../../Assets/twitter-icon.svg";
import LinkedIn from "../../../Assets/linkedin-icon.svg";
import Mail from "../../../Assets/mail-icon.svg";
import CopyToClipboard from "react-copy-to-clipboard";
// Functional component for the ShareModal
const ShareModal = ({isOpen, closeModal}) => {
// const title = `${document.title} | Advanced Dontpad`;
// Getting the current URL
const url = window.location.href;
// const iconSize = 48;
// State for tracking if the link is copied
const [isCopied, setIsCopied] = useState(false);
// useEffect to reset isCopied state after a certain time
useEffect(() => {
isCopied &&
setTimeout(() => {
setIsCopied(false);
}, 2000);
}, [isCopied]);
return (
// Wrapping div for the modal
<div>
<div className={isOpen ? 'shareModel' : ''}>
{/* Modal component for sharing */}
<Modal
open={isOpen}
onClickBackdrop={closeModal}
dataTheme="light"
className="m-2"
>
{/* Modal header */}
<Modal.Header className="font-bold">Share</Modal.Header>
{/* Modal body */}
<Modal.Body>
{/* Container for modal content */}
<div className="m-5 flex flex-col ">
{/* Close button for the modal */}
<Button
size="sm"
shape="circle"
className="bg-absolute right-2 top-2 bg-white border-none text-slate-700 text-2xl font-bold shadow-lg"
onClick={() => {
setIsCopied(false);
closeModal();
}}
>
{/* Close icon */}
<IoMdClose
onClick={closeModal}
className="absolute text-slate-500 right-3 top-3 text-2xl cursor-pointer"
/>
</Button>
{/* Container for link, copy button, and share button */}
<div className="flex items-center space-x-3 ">
{/* Displaying the current URL */}
<p className="flex items-center flex-1 border-2 p-2 text-xs text-slate-500 border-slate-300 rounded-md border-dashed">
Link:
<span className="mx-2 font-semibold text-xs overflow-x-hidden text-black">
{url}
</span>
</p>
{/* Copy to clipboard button */}
<CopyToClipboard text={url} onCopy={() => setIsCopied(true)}>
<TbCopy className="text-xl text-slate-500 scale-x-[-1] cursor-pointer" />
</CopyToClipboard>
{/* Share button */}
<BsShare className="text-xl text-slate-500 cursor-pointer" />
</div>
{/* Display message when link is copied */}
<h2 className="p-2 h-5 ml-3 text-md text-green-500 font-semibold">
{isCopied && "Link copied to clipboard"}
</h2>
{/* Container for social media share buttons */}
<div className="mt-6 flex items-center space-x-10 justify-center">
{/* Whatsapp share button */}
<WhatsappShareButton url="https://web.whatsapp.com/">
<img
src={Whatsapp}
alt="Whatsapp"
className="w-10 p-2 bg-slate-100 rounded-lg cursor-pointer"
/>
</WhatsappShareButton>
{/* Facebook share button */}
<FacebookShareButton url="https://www.facebook.com/">
<img
src={Facebook}
alt="facebook"
className="w-10 p-2 bg-slate-100 rounded-lg cursor-pointer"
/>
</FacebookShareButton>
{/* Twitter share button */}
<TwitterShareButton url="https://twitter.com/">
<img
src={Twitter}
alt="Twitter"
className="w-10 p-2 bg-slate-100 rounded-lg cursor-pointer"
/>
</TwitterShareButton>
{/* LinkedIn share button */}
<LinkedinShareButton url="https://www.linkedin.com/">
<img
src={LinkedIn}
alt="Linkedin"
className="w-10 p-2 bg-slate-100 rounded-lg cursor-pointer"
/>
</LinkedinShareButton>
{/* Email share button */}
<EmailShareButton url="https://gmail.com/">
<img
src={Mail}
alt="Mail"
className="w-10 p-2 bg-slate-100 rounded-lg cursor-pointer"
/>
</EmailShareButton>
</div>
</div>
</Modal.Body>
</Modal>
</div>
</div>
);
}
// Exporting the ShareModal component
export default ShareModal;
|
Feature: This feature describes the parameterization in Cucumber
Scenario: Passing numeric parameter to the Gherkin step
Given I have 15 and 62
When I add them
Then print result
@Regression @Smoke
Scenario: Passing String parameter to the gherkin step
Given I have two words like "India hello" and "China hi"
Then print them in alphabetic order
@Smoke
Scenario: Passing float parameters to gherkin step
Given I have two float numbers 3.14 and 5.34
Then add both float numbers
And Print float result
@Regression
Scenario: Passing list of parameters to the Gherkin step
Given I have following number:
|10|
|11|
|12|
|13|
|14|
|15|
Then print all numbers from list
@Regression
Scenario: Passing table of parameters to the gherkin step
Given I have following table:
|firstlist|11|12|13|14|15|16|
|secondlist|18|19|20|21|22|23|
Then print them in row column format
Scenario Outline:
Given I have two numbers from <row-number>
When I add them
Then verify if result is prime
Examples:
|row-number|
|1|
|2|
|3|
|4|
|5|
|6|
|
package com.devdavidm.invoicemanagerapp.productspage
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.devdavidm.invoicemanagerapp.loginpage.TextInput
import com.google.firebase.firestore.AggregateSource
import com.google.firebase.firestore.FirebaseFirestore
@Composable
fun NewProductPage(navController: NavHostController, db: FirebaseFirestore) {
BackHandler {
navController.navigate("home/Productos"){
popUpTo("new_product"){
inclusive = true
}
}
}
Surface(
color = Color(0xFFFAFAFA),
modifier = Modifier.fillMaxSize()
){
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
// Title
Text(
modifier = Modifier
.padding(top = 16.dp, start = 16.dp, bottom = 16.dp),
fontSize = 30.sp,
text = "Nuevo Producto",
color = Color(0xFF000000),
fontWeight = FontWeight.Bold
)
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(3.dp)
.background(Color.Black)
)
NewProductForm(navController, db)
}
}
}
@Composable
fun NewProductForm(navController: NavHostController, db: FirebaseFirestore) {
val context = LocalContext.current
val screenHeight = LocalConfiguration.current.screenHeightDp
// Form
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier.fillMaxSize()
) {
// brand
val brandValue = remember { mutableStateOf(TextFieldValue()) }
TextInput(label = "Marca", mutableText = brandValue)
// description
val descriptionValue = remember { mutableStateOf(TextFieldValue()) }
TextInput(label = "Descripción", mutableText = descriptionValue)
// name
val nameValue = remember { mutableStateOf(TextFieldValue()) }
TextInput(label = "Nombre", mutableText = nameValue)
// price
val priceValue = remember { mutableStateOf(TextFieldValue()) }
TextInput(label = "Precio", mutableText = priceValue, number = true)
// units
val unitsValue = remember { mutableStateOf(TextFieldValue()) }
TextInput(label = "Unidades", mutableText = unitsValue, number = true)
// type
val typeValue = remember { mutableStateOf(TextFieldValue()) }
TextInput(label = "Tipo", mutableText = typeValue)
// submit button
Spacer(modifier = Modifier.height(15.dp))
Button(
modifier = Modifier.height((screenHeight*0.06).dp),
colors = ButtonDefaults.buttonColors(
contentColor = Color(0xFFFAFAFA),
containerColor = Color(0xFF000000)
),
onClick = {
val valid = validateInfo(
brandValue.value.text,
descriptionValue.value.text,
nameValue.value.text,
priceValue.value.text,
unitsValue.value.text,
typeValue.value.text
)
if (valid) {
// Count the number of products
val tmpCountQuery = db.collection("Products").count()
tmpCountQuery.get(AggregateSource.SERVER).addOnCompleteListener { task ->
if (task.isSuccessful) {
db.collection("Products").add(
hashMapOf(
"brand" to brandValue.value.text,
"description" to descriptionValue.value.text,
"name" to nameValue.value.text,
"price" to priceValue.value.text.toInt(),
"units" to unitsValue.value.text.toInt(),
"type" to typeValue.value.text,
"num" to task.result.count.toInt() + 1
)
).addOnSuccessListener {
Toast.makeText(context, "Producto guardado", Toast.LENGTH_SHORT).show()
navController.navigate("home/Productos"){
popUpTo("new_product"){
inclusive = true
}
}
}
} else {
Toast.makeText(context, "Error al guardar el producto", Toast.LENGTH_SHORT).show()
}
}
} else {
Toast.makeText(context, "Por favor llena todos los campos", Toast.LENGTH_SHORT).show()
}
}
) {
Text(text = "Guardar")
}
}
}
fun validateInfo(
brand: String,
description: String,
name: String,
price: String,
units: String,
type: String
): Boolean {
return !(brand.isEmpty() || description.isEmpty() || name.isEmpty() || price.isEmpty() || units.isEmpty() || type.isEmpty())
}
|
import { Box, Stack, Typography, colors } from "@mui/material";
import React from "react";
import CheckIcon from "@mui/icons-material/Check";
import { red } from "@mui/material/colors";
function Card({
cardImage,
cardHeading,
cardContent1,
cardContent2,
cardContent3,
cardContent4,
}) {
return (
<div className="everythingcenter">
<img src={cardImage} className="imgSize" />
<Typography variant="h6" align="left">
{cardHeading}
</Typography>
<Stack spacing={1}>
<div style={{
display:"flex",
gap:'10px',
}}>
<CheckIcon
sx={{
color: "red",
// marginRight: "10px",
// width:'10%',
}}
/>
<Typography variant="body1" align="left">
{cardContent1}
</Typography></div>
<div style={{
display:"flex",
gap:'10px',
}}>
<CheckIcon
sx={{
color: "red",
// marginRight: "10px",
// width:'10%',
}}
/>
<Typography variant="body1" align="left">
{cardContent2}
</Typography></div>
<div style={{
display:"flex",
gap:'10px',
}}>
<CheckIcon
sx={{
color: "red",
// marginRight: "10px",
// width:'10%',
}}
/>
<Typography variant="body1" align="left">
{cardContent3}
</Typography></div>
<div style={{
display:"flex",
gap:'10px',
}}>
<CheckIcon
sx={{
color: "red",
// marginRight: "10px",
// width:'10%',
}}
/>
<Typography variant="body1" align="left">
{cardContent4}
</Typography></div>
</Stack>
</div>
);
}
export default Card;
|
#include "base.h"
class Solution {
public:
int climbStairs(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
vector<int> climb_ways(n + 1);
climb_ways[0] = 1;
climb_ways[1] = 1;
for (size_t i = 2; i <= n; ++i) {
climb_ways[i] = climb_ways[i - 1] + climb_ways[i - 2];
}
return climb_ways.back();
}
};
|
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
namespace GSpawn
{
public static class MeshCombiner
{
private class MaterialInstance
{
public Material material;
public List<MeshInstance> meshInstances = new List<MeshInstance>();
}
private class MeshInstance
{
public Mesh mesh;
public int subMeshIndex;
public Transform transform;
}
private class CombinedMeshData
{
public List<Vector3> positions;
public List<Color> colors;
public List<Vector4> tangents;
public List<Vector3> normals;
public List<Vector2> uv1;
public List<Vector2> uv2;
public List<Vector2> uv3;
public List<Vector2> uv4;
public List<int> indices;
public int currentVertexIndex;
public CombinedMeshData()
{
tangents = new List<Vector4>();
positions = new List<Vector3>();
normals = new List<Vector3>();
uv1 = new List<Vector2>();
uv2 = new List<Vector2>();
uv3 = new List<Vector2>();
uv4 = new List<Vector2>();
colors = new List<Color>();
indices = new List<int>();
}
public CombinedMeshData(int combinedNumVertsGuess)
{
tangents = new List<Vector4>(combinedNumVertsGuess);
positions = new List<Vector3>(combinedNumVertsGuess);
normals = new List<Vector3>(combinedNumVertsGuess);
uv1 = new List<Vector2>(combinedNumVertsGuess);
uv2 = new List<Vector2>(combinedNumVertsGuess);
uv3 = new List<Vector2>(combinedNumVertsGuess);
uv4 = new List<Vector2>(combinedNumVertsGuess);
colors = new List<Color>(combinedNumVertsGuess);
indices = new List<int>(combinedNumVertsGuess / 3);
}
public void reset()
{
tangents.Clear();
positions.Clear();
normals.Clear();
uv1.Clear();
uv2.Clear();
uv3.Clear();
uv4.Clear();
colors.Clear();
indices.Clear();
currentVertexIndex = 0;
}
public void addCurrentVertIndex()
{
// Note: Assumes that vertices are stored in the combined mesh buffers in the same
// way as they are encountered when reading the vertex data using indices
// from the source mesh.
indices.Add(currentVertexIndex++);
}
public void reverseWindingOrderForLastTriangle()
{
int lastIndexPtr = indices.Count - 1;
int tempIndex = indices[lastIndexPtr];
indices[lastIndexPtr] = indices[lastIndexPtr - 2];
indices[lastIndexPtr - 2] = tempIndex;
}
}
private static List<Mesh> _combinedMeshes = new List<Mesh>();
private static MeshCombineSettings _settings;
private static List<GameObject> _parentsBuffer = new List<GameObject>();
public static void combine(List<GameObject> sourceObjects, GameObject destinationParent, MeshCombineSettings settings)
{
if (sourceObjects.Count == 0)
{
EditorUtility.DisplayDialog("Missing Data", "No source objects available.", "Ok");
return;
}
if (destinationParent == null)
{
EditorUtility.DisplayDialog("Missing Data", "You must specify a destination parent that will hold all meshes that result from the mesh combine process.", "Ok");
return;
}
if (!settings.combineStaticMeshes && !settings.combineDynamicMeshes)
{
EditorUtility.DisplayDialog("Invalid Data", "You have specified that neither static nor dynamic meshes should be combined. " +
"At least one of these (i.e. static or dynamic) should be allowed.", "Ok");
return;
}
_combinedMeshes.Clear();
_settings = settings;
GameObjectEx.getParents(sourceObjects, _parentsBuffer);
List<GameObject> meshObjects = new List<GameObject>();
collectMeshObjects(_parentsBuffer, meshObjects);
if (meshObjects.Count == 0)
{
EditorUtility.DisplayDialog("Nothing Combined", "There were no meshes combined.", "Ok");
return;
}
combineMeshObjects(meshObjects, destinationParent);
}
public static void combineChildren(GameObject sourceParent, GameObject destinationParent, MeshCombineSettings settings)
{
if (sourceParent == null)
{
EditorUtility.DisplayDialog("Missing Data", "You must specify a source parent whose child meshes must be combined.", "Ok");
return;
}
if (destinationParent == null)
{
EditorUtility.DisplayDialog("Missing Data", "You must specify a destination parent that will hold all meshes that result from the mesh combine process.", "Ok");
return;
}
if (!settings.combineStaticMeshes && !settings.combineDynamicMeshes)
{
EditorUtility.DisplayDialog("Invalid Data", "You have specified that neither static nor dynamic meshes should be combined. " +
"At least one of these (i.e. static or dynamic) should be allowed.", "Ok");
return;
}
_combinedMeshes.Clear();
_settings = settings;
List<GameObject> meshObjects = new List<GameObject>();
collectMeshObjects(sourceParent, meshObjects, false);
if (meshObjects.Count == 0)
{
EditorUtility.DisplayDialog("Nothing Combined", "There were no meshes combined.", "Ok");
return;
}
combineMeshObjects(meshObjects, destinationParent);
}
private static void combineMeshObjects(List<GameObject> meshObjects, GameObject destinationParent)
{
List<MaterialInstance> materialInstances = new List<MaterialInstance>();
collectMaterialInstances(meshObjects, materialInstances);
// Note: Create the combined mesh folder if not present.
if (!FileSystem.folderExists(_settings.combinedMeshFolder)) AssetDbEx.createAssetFolder(_settings.combinedMeshFolder);
UndoEx.saveEnabledState();
UndoEx.enabled = false;
int numMaterialInstances = materialInstances.Count;
for (int i = 0; i < numMaterialInstances; ++i)
combine(materialInstances[i], destinationParent);
int numMeshObjects = meshObjects.Count;
PluginProgressDialog.begin("Post-Processing Mesh Objects");
if (_settings.disableSourceRenderers)
{
for (int i = 0; i < numMeshObjects; ++i)
{
PluginProgressDialog.updateProgress(meshObjects[i].name, (i + 1) / (float)numMeshObjects);
MeshRenderer r = meshObjects[i].getMeshRenderer();
if (r != null) r.enabled = false;
}
}
PluginProgressDialog.end();
int numCombinedMeshes = _combinedMeshes.Count;
if (numCombinedMeshes != 0)
{
PluginProgressDialog.begin("Saving Mesh Assets");
for (int i = 0; i < numCombinedMeshes; ++i)
{
Mesh mesh = _combinedMeshes[i];
PluginProgressDialog.updateProgress(mesh.name, (i + 1) / (float)numCombinedMeshes);
AssetDatabase.CreateAsset(mesh, _settings.combinedMeshFolder + "/" + mesh.name + ".asset");
}
AssetDatabase.SaveAssets();
PluginProgressDialog.end();
}
UndoEx.restoreEnabledState();
}
private static void collectMeshObjects(List<GameObject> parentObjects, List<GameObject> meshObjects)
{
meshObjects.Clear();
PluginProgressDialog.begin("Collecting Mesh Objects");
int numParentObjects = parentObjects.Count;
for (int i = 0; i < numParentObjects; ++i)
{
var parent = parentObjects[i];
collectMeshObjects(parent, meshObjects, true);
PluginProgressDialog.updateProgress(parent.name, (i + 1) / (float)numParentObjects);
}
PluginProgressDialog.end();
}
private static void collectMeshObjects(GameObject sourceParent, List<GameObject> meshObjects, bool append)
{
if (!append)
{
meshObjects.Clear();
PluginProgressDialog.begin("Collecting Mesh Objects");
var meshRenderers = sourceParent.GetComponentsInChildren<MeshRenderer>(false);
int numRenderers = meshRenderers.Length;
for (int i = 0; i < numRenderers; ++i)
{
var r = meshRenderers[i];
PluginProgressDialog.updateProgress(r.gameObject.name, (i + 1) / (float)numRenderers);
if (canMeshObjectBeCombined(r, sourceParent))
meshObjects.Add(r.gameObject);
}
PluginProgressDialog.end();
}
else
{
var meshRenderers = sourceParent.GetComponentsInChildren<MeshRenderer>(false);
int numRenderers = meshRenderers.Length;
for (int i = 0; i < numRenderers; ++i)
{
var r = meshRenderers[i];
if (canMeshObjectBeCombined(r, sourceParent))
meshObjects.Add(r.gameObject);
}
}
}
private static void collectMaterialInstances(List<GameObject> meshObjects, List<MaterialInstance> materialInstances)
{
materialInstances.Clear();
var materialInstanceMap = new Dictionary<Material, MaterialInstance>();
PluginProgressDialog.begin("Collecting Material Instances");
int numMeshObjects = meshObjects.Count;
for (int i = 0; i < numMeshObjects; ++i)
{
var meshObject = meshObjects[i];
PluginProgressDialog.updateProgress(meshObject.name, (i + 1) / (float)numMeshObjects);
MeshFilter meshFilter = meshObject.getMeshFilter();
MeshRenderer meshRenderer;
if (_settings.combineLODs)
{
int lodIndex = meshObject.findLODIndexAndMeshRenderer(out meshRenderer);
if (lodIndex < 0) meshRenderer = meshObject.getMeshRenderer();
else if (lodIndex != _settings.lodIndex) continue;
}
else meshRenderer = meshObject.getMeshRenderer();
Mesh sharedMesh = meshFilter.sharedMesh;
int numSharedMaterials = meshRenderer.sharedMaterials.Length;
for (int subMeshIndex = 0; subMeshIndex < sharedMesh.subMeshCount; ++subMeshIndex)
{
// Note: How can this happen?
if (subMeshIndex >= numSharedMaterials) break;
// Note: Only accepts triangle meshes.
if (sharedMesh.GetTopology(subMeshIndex) != MeshTopology.Triangles) continue;
Material material = meshRenderer.sharedMaterials[subMeshIndex];
MaterialInstance materialInstance;
if (!materialInstanceMap.ContainsKey(material))
{
materialInstance = new MaterialInstance();
materialInstance.material = material;
materialInstanceMap.Add(material, materialInstance);
materialInstances.Add(materialInstance);
}
else materialInstance = materialInstanceMap[material];
var meshInstance = new MeshInstance();
meshInstance.mesh = sharedMesh;
meshInstance.subMeshIndex = subMeshIndex;
meshInstance.transform = meshObject.transform;
materialInstance.meshInstances.Add(meshInstance);
}
}
PluginProgressDialog.end();
}
private static bool canMeshObjectBeCombined(Renderer renderer, GameObject sourceParent)
{
if (!renderer.enabled) return false;
GameObject gameObject = renderer.gameObject;
if (!gameObject.activeInHierarchy) return false;
if (!_settings.combineStaticMeshes && gameObject.isStatic) return false;
if (!_settings.combineDynamicMeshes && !gameObject.isStatic) return false;
MeshFilter meshFilter = gameObject.getMeshFilter();
if (meshFilter == null || meshFilter.sharedMesh == null) return false;
if (_settings.ignoreMultiLevelHierarchies)
{
if (sourceParent != null)
{
if ((gameObject.transform.parent != null && gameObject.transform.parent.gameObject != sourceParent) ||
gameObject.transform.childCount != 0) return false;
}
else if (gameObject.transform.parent != null || gameObject.transform.childCount != 0) return false;
}
if (!_settings.combineLODs)
{
if (gameObject.isPartOfLODGroup()) return false;
}
return true;
}
private static int getMaxNumberOfMeshVerts()
{
if (_settings.combinedIndexFormat == MeshCombineIndexFormat.UInt16)
{
if (_settings.generateLightmapUVs) return 32000;
return 65000;
}
else
{
if (_settings.generateLightmapUVs) return 4000000;
return 8000000;
// Note: These values seem to be too large and cause Unity to crash
// when saving the meshes as assets.
/*
if (_settings.generateLightmapUVs) return 1000000000;
return 2000000000;*/
}
}
private static void combine(MaterialInstance materialInstance, GameObject destinationParent)
{
List<MeshInstance> meshInstances = materialInstance.meshInstances;
if (meshInstances.Count == 0) return;
int maxNumMeshVerts = getMaxNumberOfMeshVerts();
var combinedMeshData = new CombinedMeshData();
PluginProgressDialog.begin("Combining Meshes for Material: " + materialInstance.material.name);
List<GameObject> combinedMeshObjects = new List<GameObject>();
for (int meshInstanceIndex = 0; meshInstanceIndex < meshInstances.Count; ++meshInstanceIndex)
{
MeshInstance meshInstance = meshInstances[meshInstanceIndex];
Mesh mesh = meshInstance.mesh;
if (mesh.vertexCount == 0) continue;
PluginProgressDialog.updateProgress("Mesh: " + meshInstance.mesh.name, (meshInstanceIndex + 1) / (float)meshInstances.Count);
Matrix4x4 worldMatrix = meshInstance.transform.localToWorldMatrix;
Matrix4x4 worldInverseTranspose = worldMatrix.inverse.transpose;
Vector3 worldScale = meshInstance.transform.lossyScale;
bool reverseVertexWindingOrder = (worldScale.countNegative() % 2 != 0);
int[] subMeshVertIndices = mesh.GetTriangles(meshInstance.subMeshIndex);
if (subMeshVertIndices.Length == 0) continue;
Vector3[] positions = mesh.vertices;
Color[] colors = mesh.colors;
Vector4[] tangents = mesh.tangents;
Vector3[] normals = mesh.normals;
Vector2[] uv1 = mesh.uv;
Vector2[] uv2 = mesh.uv2;
Vector2[] uv3 = mesh.uv3;
Vector2[] uv4 = mesh.uv4;
foreach (var vertIndex in subMeshVertIndices)
{
if (tangents.Length != 0)
{
Vector3 transformedTangent = new Vector3(tangents[vertIndex].x, tangents[vertIndex].y, tangents[vertIndex].z);
transformedTangent = worldInverseTranspose.MultiplyVector(transformedTangent);
transformedTangent.Normalize();
combinedMeshData.tangents.Add(new Vector4(transformedTangent.x, transformedTangent.y, transformedTangent.z, tangents[vertIndex].w));
}
if (normals.Length != 0)
{
Vector3 transformedNormal = worldInverseTranspose.MultiplyVector(normals[vertIndex]);
transformedNormal.Normalize();
combinedMeshData.normals.Add(transformedNormal);
}
if (positions.Length != 0) combinedMeshData.positions.Add(worldMatrix.MultiplyPoint(positions[vertIndex]));
if (colors.Length != 0) combinedMeshData.colors.Add(colors[vertIndex]);
if (uv1.Length != 0) combinedMeshData.uv1.Add(uv1[vertIndex]);
if (uv3.Length != 0) combinedMeshData.uv2.Add(uv3[vertIndex]);
if (uv4.Length != 0) combinedMeshData.uv3.Add(uv4[vertIndex]);
if (uv2.Length != 0 && !_settings.generateLightmapUVs) combinedMeshData.uv2.Add(uv2[vertIndex]);
combinedMeshData.addCurrentVertIndex();
int numIndices = combinedMeshData.indices.Count;
if (reverseVertexWindingOrder && numIndices % 3 == 0) combinedMeshData.reverseWindingOrderForLastTriangle();
int numMeshVerts = combinedMeshData.positions.Count;
if (combinedMeshData.indices.Count % 3 == 0 && (maxNumMeshVerts - numMeshVerts) < 3)
{
combinedMeshObjects.Add(createCombinedMeshObject(combinedMeshData, materialInstance, destinationParent));
combinedMeshData.reset();
}
}
}
PluginProgressDialog.end();
combinedMeshObjects.Add(createCombinedMeshObject(combinedMeshData, materialInstance, destinationParent));
}
private static GameObject createCombinedMeshObject(CombinedMeshData combinedMeshData, MaterialInstance materialInstance, GameObject destinationParent)
{
Mesh combinedMesh = createCombinedMesh(combinedMeshData, materialInstance);
string baseName = _settings.combinedMeshObjectBaseName;
if (baseName == null) baseName = string.Empty;
GameObject combinedMeshObject = new GameObject(baseName + materialInstance.material.name);
combinedMeshObject.transform.parent = destinationParent.transform;
combinedMeshObject.isStatic = _settings.combineAsStatic ? true : false;
MeshFilter meshFilter = combinedMeshObject.AddComponent<MeshFilter>();
meshFilter.sharedMesh = combinedMesh;
MeshRenderer meshRenderer = combinedMeshObject.AddComponent<MeshRenderer>();
meshRenderer.sharedMaterial = materialInstance.material;
var boundsQConfig = ObjectBounds.QueryConfig.defaultConfig;
boundsQConfig.objectTypes = GameObjectType.Mesh;
AABB combinedAABB = ObjectBounds.calcWorldAABB(combinedMeshObject, boundsQConfig);
Vector3 meshPivotPt;
if (_settings.combinedMeshPivot == MeshCombinePivot.Center) meshPivotPt = combinedAABB.center;
else if (_settings.combinedMeshPivot == MeshCombinePivot.BackCenter) meshPivotPt = Box3D.calcFaceCenter(combinedAABB.center, combinedAABB.size, Box3DFace.Back);
else if (_settings.combinedMeshPivot == MeshCombinePivot.FrontCenter) meshPivotPt = Box3D.calcFaceCenter(combinedAABB.center, combinedAABB.size, Box3DFace.Front);
else if (_settings.combinedMeshPivot == MeshCombinePivot.BottomCenter) meshPivotPt = Box3D.calcFaceCenter(combinedAABB.center, combinedAABB.size, Box3DFace.Bottom);
else if (_settings.combinedMeshPivot == MeshCombinePivot.TopCenter) meshPivotPt = Box3D.calcFaceCenter(combinedAABB.center, combinedAABB.size, Box3DFace.Top);
else if (_settings.combinedMeshPivot == MeshCombinePivot.LeftCenter) meshPivotPt = Box3D.calcFaceCenter(combinedAABB.center, combinedAABB.size, Box3DFace.Left);
else meshPivotPt = Box3D.calcFaceCenter(combinedAABB.center, combinedAABB.size, Box3DFace.Right);
combinedMeshObject.setMeshPivotPoint(combinedMesh, meshPivotPt);
return combinedMeshObject;
}
private static Mesh createCombinedMesh(CombinedMeshData combinedMeshData, MaterialInstance materialInstance)
{
Mesh combinedMesh = new Mesh();
combinedMesh.name = _settings.combinedMeshBaseName + materialInstance.material.name + "_" + combinedMesh.GetHashCode();
combinedMesh.indexFormat = _settings.combinedIndexFormat == MeshCombineIndexFormat.UInt32 ? IndexFormat.UInt32 : IndexFormat.UInt16;
combinedMesh.vertices = combinedMeshData.positions.ToArray();
if (combinedMeshData.tangents.Count != 0) combinedMesh.tangents = combinedMeshData.tangents.ToArray();
if (combinedMeshData.normals.Count != 0) combinedMesh.normals = combinedMeshData.normals.ToArray();
if (combinedMeshData.uv1.Count != 0) combinedMesh.uv = combinedMeshData.uv1.ToArray();
if (combinedMeshData.uv3.Count != 0) combinedMesh.uv3 = combinedMeshData.uv3.ToArray();
if (combinedMeshData.uv4.Count != 0) combinedMesh.uv4 = combinedMeshData.uv4.ToArray();
combinedMesh.SetIndices(combinedMeshData.indices.ToArray(), MeshTopology.Triangles, 0);
if (_settings.generateLightmapUVs) Unwrapping.GenerateSecondaryUVSet(combinedMesh);
else if (combinedMeshData.uv2.Count != 0) combinedMesh.uv2 = combinedMeshData.uv2.ToArray();
combinedMesh.UploadMeshData(!_settings.combinedMeshesAreReadable);
_combinedMeshes.Add(combinedMesh);
return combinedMesh;
}
}
}
#endif
|
From: John Wehle <john@feith.com>
Date: Thu, 21 Oct 1999 19:56:53 -0400 (EDT)
Message-Id: <199910212356.TAA12563@jwlab.FEITH.COM>
To: schaefer@vulcan.alphanet.ch
Subject: Bash version of Vgetty.pm
Cc: kas@fi.muni.cz
Content-Type: text
I found that starting the perl interpeter from vgetty takes too long
(at least on the tiny machine in question) so I created a bash version
of Vgetty.pm which you may find useful.
A sample script which uses it is:
. `dirname $0`/Vgetty.sh
finish () {
v_stop
v_waitfor 'READY'
v_shutdown
exit 0
}
v_add_handler 'BUSY_TONE' 'hangup' 'finish'
v_add_handler 'DIAL_TONE' 'hangup' 'finish'
v_add_handler 'LOOP_POLARITY_CHANGE' 'hangup' 'finish'
v_enable_events
while true
do
announcement=`v_readnum "$voicedir/messages/main_menu.rmd" 2 2` \
|| break
case "$announcement" in
1) v_play_and_wait "$voicedir/messages/announcement_1.rmd"
;;
2) v_play_and_wait "$voicedir/messages/announcement_2.rmd"
;;
3) v_play_and_wait "$voicedir/messages/announcement_3.rmd"
;;
*) ;;
esac
done
v_shutdown
exit 0
-- John
--------------------------<-----------------------<----------------------
#!/bin/sh
# This is a shell archive (produced by GNU shar 4.0).
# To extract the files from this archive, save it to some FILE, remove
# everything before the `!/bin/sh' line above, then type `sh FILE'.
#
# Made on 1999-10-21 19:52 EDT by <john@pecan.FEITH.COM>.
# Source directory was `/home/john'.
#
# Existing files will *not* be overwritten unless `-c' is specified.
#
# This shar contains:
# length mode name
# ------ ---------- ------------------------------------------
# 6533 -rw-r--r-- Vgetty.sh
#
touch -am 1231235999 $$.touch >/dev/null 2>&1
if test ! -f 1231235999 && test -f $$.touch; then
shar_touch=touch
else
shar_touch=:
echo 'WARNING: not restoring timestamps'
fi
rm -f 1231235999 $$.touch
#
if test -f 'Vgetty.sh' && test X"$1" != X"-c"; then
echo 'x - skipping Vgetty.sh (File already exists)'
else
echo 'x - extracting Vgetty.sh (text)'
sed 's/^X//' << 'SHAR_EOF' > 'Vgetty.sh' &&
# Bash version of Vgetty.pm
#
# Copyright (c) 1999 John Wehle <john@feith.com>. All rights reserved.
# This package is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
#
# Derived from:
#
# $Id: Vgetty.sh.EXAMPLE,v 1.1 2000/06/11 16:01:44 marcs Exp $
#
# Copyright (c) 1998 Jan "Yenya" Kasprzak <kas@fi.muni.cz>. All rights
# reserved. This package is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
X
testing=0
log_file='/var/log/voicelog'
X
event_names="BONG_TONE|BUSY_TONE|CALL_WAITING|DIAL_TONE|\
X DATA_CALLING_TONE|DATA_OR_FAX_DETECTED|FAX_CALLING_TONE|\
X HANDSET_ON_HOOK|LOOP_BREAK|LOOP_POLARITY_CHANGE|NO_ANSWER|\
X NO_DIAL_TONE|NO_VOICE_ENERGY|RING_DETECTED|RINGBACK_DETECTED|\
X RECEIVED_DTMF|SILENCE_DETECTED|SIT_TONE|TDD_DETECTED|\
X VOICE_DETECTED|UNKNOWN_EVENT"
X
v_log () {
X case "$testing" in
X 0|'') ;;
X *) echo "$*" >>"$log_file"
X ;;
X esac
}
X
_received_input=""
X
# The basic two functions (a low-level interface);
v_receive () {
X local dtmf
X local input
X local var
X
X while true
X do
X read input <&$VOICE_INPUT
X v_log "received: $input"
X eval "case '$input' in \
X $event_names) ;; \
X *) break \
X ;; \
X esac"
X # Handle the event:
X dtmf=''
X case "$input" in
X RECEIVED_DTMF) read dtmf <&"$VOICE_INPUT"
X v_log "DTMF $dtmf"
X ;;
X esac
X for var in `set`
X do
X var="${var%%=*}"
X case "$var" in
X EVENT_${input}_*) v_log "Running handler ${var##EVENT_${input}_} for event $input"
X eval \$$var '"$input"' '"$dtmf"'
X v_log "Handler ${var##EVENT_${input}_} for event $input finished."
X ;;
X esac
X done
X done
X _received_input=$input
X return 0
}
X
v_send () {
X local output
X
X output="$1"
X echo "$output" >&$VOICE_OUTPUT
X kill -PIPE "$VOICE_PID"
X v_log "v_send: $output"
}
X
v_expect () {
X local expected
X local received
X
X v_log "expecting: $*"
X v_receive || return 1
X for expected in "$@"
X do
X if [ "$_received_input" = "$expected" ]
X then
X echo "$_received_input"
X return 0
X fi
X done
X return 1
}
X
v_waitfor () {
X local string
X
X string="$1"
X while true
X do
X if v_expect "$string" > /dev/null
X then
X break
X fi
X done
}
X
v_chat () {
X local cmd
X local receive
X
X receive=0
X for cmd in "$@"
X do
X receive=$(($receive ^ 1))
X case "$cmd" in
X '') continue
X ;;
X esac
X case "$receive" in
X 1) v_expect "$cmd" > /dev/null || return 1
X ;;
X *) v_send "$cmd"
X ;;
X esac
X done
X return 0
}
X
# Initial chat
v_init () {
X v_chat 'HELLO SHELL' 'HELLO VOICE PROGRAM' 'READY'
}
X
# Setting the voice device
v_device () {
X local dev
X
X dev="$1"
X v_log "attempting to set device $dev"
X v_chat '' "DEVICE $dev" 'READY' || return
X DEVICE="$dev"
X v_log "sucessfully set device $dev"
}
X
v_shutdown () {
X v_chat '' 'GOODBYE' 'GOODBYE SHELL'
}
X
v_enable_events () {
X v_chat '' 'ENABLE EVENTS' 'READY'
}
X
v_disable_events () {
X v_chat '' 'DISABLE EVENTS' 'READY'
}
X
v_beep () {
X local freq
X local len
X
X freq="$1"
X len="$2"
X v_chat '' "BEEP $freq $len" 'BEEPING'
}
X
v_dial () {
X local num
X
X num="$1"
X v_chat '' "DIAL $num" 'DIALING'
}
X
v_getty () {
X local id
X
X v_chat '' 'GET TTY' || return 1
X v_receive || return 1
X id="$_received_input"
X v_expect 'READY' > /dev/null || return 1
X echo "$id"
X return 0
}
X
v_modem_type () {
# To be implemented in vgetty first.
X return 1
}
X
v_autostop () {
X local arg
X
X arg="$1"
X v_chat '' "AUTOSTOP $arg" 'READY'
}
X
v_play () {
X local file
X
X file="$1"
X v_chat '' "PLAY $file" 'PLAYING'
}
X
v_record () {
X local file
X
X file="$1"
X v_chat '' "RECORD $file" 'RECORDING'
}
X
v_wait () {
X local sec
X
X sec="$1"
X v_chat '' "WAIT $sec" 'WAITING'
}
X
v_stop () {
X v_send 'STOP' # Nechceme READY.
}
X
v_add_handler () {
X local event
X local func
X local name
X
X event="$1"
X name="$2"
X func="$3"
X eval "case '$event' in \
X $event_names) ;; \
X *) v_log 'v_add_handler: unknown event $event'; \
X return 1 \
X ;; \
X esac"
X eval "EVENT_${event}_${name}"="$func"
X return 0
}
X
v_del_handler () {
X local event
X local name
X
X event="$1"
X name="$2"
X eval "case '$event' in \
X $event_names) ;; \
X *) v_log 'v_del_handler: unknown event $event'; \
X return 1 \
X ;; \
X esac"
X eval "case \"\${EVENT_${event}_${name}}\" in \
X '') v_log 'v_del_handler: trying to delete nonexistent handler $name' \
X ;; \
X *) unset 'EVENT_${event}_${name}' \
X ;; \
X esac"
X return 0
}
X
v_play_and_wait () {
X local file
X
X file="$1"
X v_play "$file"
X v_waitfor 'READY'
}
X
#####################################################################
# The readnum routine, its private variables and the event handler. #
#####################################################################
X
_readnum_number="" # The number itself. Filled in by the event handler.
_readnum_pound=0 # Was the '#' key pressed?
_readnum_recursion=0 # Is the event handler already executing?
_readnum_timeout=10 # The value of the timeout. Filled in by v_readnum.
X
# Event handler. Just adds key to the $_readnum_number.
_readnum_event () {
X local dtmf
X local input
X
X input="$1" # Unused. Should be 'RECEIVED_DTMF'.
X dtmf="$2"
X
X case "$_readnum_pound" in
X 1) return
X ;;
X esac
X case "$dtmf" in
X '#') _readnum_pound=1
X ;;
X *) _readnum_number="$_readnum_number$dtmf"
X ;;
X esac
X case "$_readnum_recursion" in
X 0) _readnum_recursion=1
X v_stop
X v_waitfor 'READY'
X case "$_readnum_pound" in
X 1) v_log "_readnum_event(): Got #; stopping"
X v_send "WAIT 0"
X v_waitfor WAITING
X return
X ;;
X esac
X v_send "WAIT $_readnum_timeout"
X v_waitfor WAITING
X _readnum_recursion=0
X ;;
X esac
}
X
v_readnum () {
X local message
X local timeout
X local times
X
X message="$1"
X timeout="$2"
X times="$3"
X
X case "$timeout" in
X 0|'') timeout=10
X ;;
X esac
X case "$times" in
X 0|'') times=3
X ;;
X esac
X
X _readnum_number=""
X _readnum_pound=0
X _readnum_recursion=0
X _readnum_timeout="$timeout"
X
X # Install the handler.
X v_add_handler 'RECEIVED_DTMF' 'readnum' _readnum_event
X while [ -z "$_readnum_number" -a "$_readnum_pound" -eq 0 ]
X do
X times=$(($times - 1))
X if [ "$times" -eq "-1" ]
X then
X break;
X fi
X v_play_and_wait "$message"
X if [ -n "$_readnum_number" -o "$_readnum_pound" -ne 0 ]
X then
X break
X fi
X v_wait "$_readnum_timeout"
X v_waitfor 'READY'
X done
X v_del_handler 'RECEIVED_DTMF' 'readnum'
X case "$times" in
X -1) return 1
X ;;
X esac
X echo "$_readnum_number"
X return 0
}
X
v_log "-----------"
v_log "### Pid $$ opening log"
v_log "----------"
v_init
SHAR_EOF
$shar_touch -am 1021195299 'Vgetty.sh' &&
chmod 0644 'Vgetty.sh' ||
echo 'restore of Vgetty.sh failed'
shar_count="`wc -c < 'Vgetty.sh'`"
test 6533 -eq "$shar_count" ||
echo "Vgetty.sh: original size 6533, current size $shar_count"
fi
exit 0
|
'use client'
import { Button } from 'flowbite-react';
import React, { useEffect, useState } from 'react';
function Liveclass() {
const [classes, setClasses] = useState([]);
useEffect(() => {
fetch('https://db-lern-server.vercel.app/liveclass')
.then((response) => response.json())
.then((data) => setClasses(data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<div>
<h1>Live class</h1>
<div className="border rounded-lg overflow-hidden dark:bg-gray-900">
<table className="w-full table-auto">
<thead className="bg-gray-100 dark:bg-gray-800">
<tr>
<th className="px-6 py-4 text-left font-medium text-gray-900 dark:text-gray-50">Inex No</th>
<th className="px-6 py-4 text-left font-medium text-gray-900 dark:text-gray-50">Description</th>
<th className="px-6 py-4 text-left font-medium text-gray-900 dark:text-gray-50">Date</th>
<th className="px-6 py-4 text-left font-medium text-gray-900 dark:text-gray-50">Join Class</th>
{/* <th className="px-6 py-4 text-left font-medium text-gray-900 dark:text-gray-50">Action</th> */}
</tr>
</thead>
<tbody>
{Array.isArray(classes) && classes.length > 0 ? (
classes.map((liveClass,index) => (
<tr key={liveClass._id} className="border-t border-gray-200 dark:border-gray-800">
<td className="px-6 py-4 font-medium text-white"> {index}</td>
<td className="px-6 py-4 text-white text-lg dark:text-gray-400">
{liveClass.description}
</td>
<td className="px-6 py-4 text-lg text-white">
{new Date(liveClass.time).toLocaleString()}
</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2">
<Button
className="border-blue-500 text-white hover:bg-blue-500 hover:text-white dark:border-gray-800 dark:text-gray-50 dark:hover:bg-blue-500 dark:hover:text-gray-50"
size="sm"
variant="outline"
onClick={() => window.open(liveClass.link, '_blank')}
>
Join Live
</Button>
</div>
</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2">
{/* <Button
className="bg-red-600 text-gray-50 hover:bg-red-700 dark:bg-red-600 dark:text-gray-50 dark:hover:bg-red-700"
size="sm"
variant="destructive"
>
Delete
</Button> */}
</div>
</td>
</tr>
))
) : (
<tr>
<td colSpan="5" className="px-6 py-4 text-center text-white">
No live classes available.
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
export default Liveclass;
|
//
// ProfileAddSummaryVC.swift
// workntour
//
// Created by Chris Petimezas on 14/11/22.
//
import UIKit
import SharedKit
class ProfileAddSummaryVC: BaseVC<ProfileAddSummaryViewModel, ProfileCoordinator> {
// MARK: - Outlets
@IBOutlet weak var mainView: UIView! {
didSet {
mainView.layer.borderColor = UIColor.appColor(.purple).cgColor
mainView.layer.borderWidth = 1
mainView.layer.cornerRadius = 8
}
}
@IBOutlet weak var descriptionTextView: UITextView! {
didSet {
descriptionTextView.dataDetectorTypes = .link
descriptionTextView.returnKeyType = .done
descriptionTextView.delegate = self
}
}
@IBOutlet weak var limitLabel: UILabel!
@IBOutlet weak var placeholderLabel: UILabel!
// MARK: - Life Cycle
override func viewWillFirstAppear() {
super.viewWillFirstAppear()
guard let viewModel else { return }
setupNavigationBar(mainTitle: viewModel.data.navigationBarTitle)
let saveAction = UIBarButtonItem(
title: "save".localized(),
style: .plain,
target: self,
action: #selector(saveBtnTapped)
)
navigationItem.rightBarButtonItems = [saveAction]
navigationItem.rightBarButtonItem?.isEnabled = false
}
override func setupUI() {
super.setupUI()
guard let viewModel else { return }
let currentCharacters = viewModel.data.description?.count ?? 0
limitLabel.text = "\(currentCharacters)/\(viewModel.data.charsLimit)"
if let currentText = viewModel.data.description {
placeholderLabel.isHidden = true
descriptionTextView.text = currentText
}
else {
placeholderLabel.text = viewModel.data.placeholder
}
}
// MARK: - Actions
@objc private func saveBtnTapped() {
let description = descriptionTextView.text.trimmingCharacters(in: .whitespaces)
guard var profileDto = UserDataManager.shared.retrieve(TravelerProfileDto.self),
!description.isEmpty
else {
return
}
profileDto.description = description
self.coordinator?.navigate(to: .updateTravelerProfile(profileDto))
}
}
// MARK: - UITextViewDelegate
extension ProfileAddSummaryVC: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
placeholderLabel.isHidden = true
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let viewModel else { return false }
if text == "\n" { // For 'Done' keyboard key
textView.resignFirstResponder()
return false
}
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
let shouldChangeText = newText.count <= viewModel.data.charsLimit
if shouldChangeText {
limitLabel.text = "\(newText.count)/\(viewModel.data.charsLimit)"
}
// Enable navigationBarRightItem when current chars are not .zero
navigationItem.rightBarButtonItem?.isEnabled = newText.count > .zero ? true : false
return shouldChangeText
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.