text
stringlengths 184
4.48M
|
|---|
Review the generated project files
* The settings.gradle file is heavily commented, but has only one active line:
rootProject.name = 'demo'
This sets the name of the root project to "demo", which overrides the default behavior of naming the project after the directory it’s in.
* The generated build.gradle file also has many comments
plugins {
id 'java'
id 'application'
}
repositories {
jcenter() (1)
}
dependencies {
implementation 'com.google.guava:guava:26.0-jre' (2)
testImplementation 'junit:junit:4.12' (3)
}
mainClassName = 'demo.App' (4)
=>
(1) public Bintray Artifactory repository.
(2) Google Guava library
(3) JUnit testing library
(4) Class with "main" method (used by Application plugin)
The build file adds the java and application plugins.
Main Class Called by Application plugin "run" task
* Build
$ ./gradlew build
The first time you run the wrapper script, gradlew,
there may be a delay while that version of gradle is downloaded and stored locally in your ~/.gradle/wrapper/dists folder.
The first time you run the build, Gradle will check whether or not you already have the Guava and JUnit libraries in your cache under your ~/.gradle directory.
If not, the libraries will be downloaded and stored there. The next time you run the build, the cached versions will be used.
The build task compiles the classes, runs the tests, and generates a test report.
$ ./gradles tasks
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../bloc/feed/like_post/like_post_bloc.dart';
import '../bloc/feed/like_post/like_post_event.dart';
import '../bloc/feed/like_post/like_post_state.dart';
import '../model/post_model.dart';
Widget itemOfPost(BuildContext context, Post post) {
return Container(
color: Colors.white,
child: Column(
children: [
const Divider(),
//#user info
Container(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(40),
child: post.img_user.isEmpty
? const Image(
image: AssetImage("assets/images/ic_person.png"),
width: 40,
height: 40,
fit: BoxFit.cover,
)
: Image.network(
post.img_user,
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
const SizedBox(width: 10),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
post.fullname,
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
const SizedBox(height: 3),
Text(
post.date,
style: const TextStyle(fontWeight: FontWeight.normal),
),
],
),
],
),
post.mine
? IconButton(
icon: const Icon(Icons.more_horiz),
onPressed: () {
// context
// .read<ItemPostBloc>()
// .add(RemovePostEvent(context, post));
},
)
: const SizedBox.shrink(),
],
),
),
//#post image
const SizedBox(height: 8),
GestureDetector(
onDoubleTap: () {
if (post.liked) {
context.read<LikePostBloc>().add(UnLikePostEvent(post: post));
} else {
context.read<LikePostBloc>().add(LikePostEvent(post: post));
}
},
child: CachedNetworkImage(
width: MediaQuery.of(context).size.width,
imageUrl: post.img_post,
placeholder: (context, url) => const Center(
child: CircularProgressIndicator(),
),
errorWidget: (context, url, error) => const Icon(Icons.error),
fit: BoxFit.cover,
),
),
//#like share
Row(
children: [
Row(
children: [
IconButton(
onPressed: () {
if (post.liked) {
context
.read<LikePostBloc>()
.add(UnLikePostEvent(post: post));
} else {
context
.read<LikePostBloc>()
.add(LikePostEvent(post: post));
}
},
icon: BlocBuilder<LikePostBloc, LikeState>(
builder: (context, state) {
return post.liked
? const Icon(
Icons.favorite,
color: Colors.red,
)
: const Icon(
Icons.favorite_border,
color: Colors.black,
);
},
),
// color: post.liked ? Colors.red : Colors.black,
),
IconButton(
onPressed: () {},
icon: const Icon(
Icons.share,
),
),
],
)
],
),
//#caption
Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
child: RichText(
softWrap: true,
overflow: TextOverflow.visible,
text: TextSpan(
text: post.caption,
style: const TextStyle(color: Colors.black),
),
),
),
],
),
);
}
|
import re
# Load file
with open('day1/input', 'r') as f:
data = f.readlines()
part1_calibrations = []
for line in data:
calibration = ""
# Find first digit in string
for character in line:
if character.isdigit():
calibration += character
break
# Find last digit in string
for character in reversed(line):
if character.isdigit():
calibration += character
break
part1_calibrations.append(int(calibration))
print(sum(part1_calibrations))
part2_calibrations = []
digit_finder = re.compile(r'(?=(one|two|three|four|five|six|seven|eight|nine|zero|\d))')
def convert_to_digit(value: str) -> str:
match value:
case "one":
return "1"
case "two":
return "2"
case "three":
return "3"
case "four":
return "4"
case "five":
return "5"
case "six":
return "6"
case "seven":
return "7"
case "eight":
return "8"
case "nine":
return "9"
case _:
return value
# Part 2
for line in data:
calibration = ""
matches = digit_finder.findall(line)
# Find first digit in string
calibration += convert_to_digit(matches[0])
# Find last digit in string
calibration += convert_to_digit(matches[-1])
part2_calibrations.append(int(calibration))
print(sum(part2_calibrations))
|
import uuid
import socket
from typing import Literal
from pydantic_settings import BaseSettings, SettingsConfigDict
KAFKA_TOPICS = {
"app.hearthbeats.event.proto.v1": {
"topic_creation_config": {
"num_partitions": 2,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 100000
}
},
"f1.session-request.event.proto.v1": {
"topic_creation_config": {
"num_partitions": 2,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 604800000
}
},
"f1.session-request-status.event.proto.v1": {
"topic_creation_config": {
"num_partitions": 2,
},
"topic_alter_config": {
"cleanup.policy": "compact",
"retention.ms": -1,
"delete.retention.ms": 300000
}
},
"f1.circute-info.records.proto.v1": {
"topic_creation_config": {
"num_partitions": 1,
},
"topic_alter_config": {
"cleanup.policy": "compact",
"retention.ms": -1,
"delete.retention.ms": 300000
}
},
"f1.laps.event.proto.v1": {
"topic_creation_config": {
"num_partitions": 10,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 900000
}
},
"f1.car.data.proto.v1": {
"topic_creation_config": {
"num_partitions": 8,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 900000
}
},
"f1.weather.data.proto.v1": {
"topic_creation_config": {
"num_partitions": 2,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 900000
}
},
"f1.position.data.proto.v1": {
"topic_creation_config": {
"num_partitions": 8,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 900000
}
},
"f1.session-status.event.proto.v1": {
"topic_creation_config": {
"num_partitions": 2,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 900000
}
},
"f1.track-status.event.proto.v1": {
"topic_creation_config": {
"num_partitions": 2,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 900000
}
},
"f1.race-control-messages.event.proto.v1": {
"topic_creation_config": {
"num_partitions": 2,
},
"topic_alter_config": {
"cleanup.policy": "delete",
"retention.ms": 900000
}
}
}
class ConsumerConfig(BaseSettings):
BOOTSTRAP_SERVERS: str = "localhost:9092"
SCHEMA_REGISTRY_URL: str = "http://localhost:8081"
TOPIC: str = "f1.session-request.event.proto.v1"
GROUP_ID: str = "f1.requests"
AUTO_COMMIT: bool = False
AUTO_COMMIT_INTERVAL_MS: int = 1000
AUTO_OFFSET_RESET: Literal["earliest", "latest", None] = "earliest"
class ProducerConfig(BaseSettings):
BOOTSTRAP_SERVERS: str = "localhost:9092"
SCHEMA_REGISTRY_URL: str = "http://localhost:8081"
TOPIC_CIRCUTE_INFO: str = "f1.circute-info.records.proto.v1"
HEARTHBEAT_TOPIC: str = "app.hearthbeats.event.proto.v1"
class Config(BaseSettings):
LOG_LEVEL: str = "INFO"
NAME: str = socket.gethostname()
CONSUMER: ConsumerConfig = ConsumerConfig()
PRODUCER: ProducerConfig = ProducerConfig()
model_config = SettingsConfigDict(env_prefix="F1_", env_nested_delimiter="__")
|
import User from "../models/User.js";
//bcrypt คือตัวเข้ารหัสข้อมูล
import bcrypt from "bcryptjs";
import { createError } from "../utils/error.js";
import jwt from "jsonwebtoken";
export const register = async (req, res, next) => {
try {
//นำข้อมูล password มาเข้ารหัส
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.password, salt);
//เรียกใช้ schema
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: hash,
});
await newUser.save();
res.status(200).send("ข้อมูลผู้ใช้งานได้ถูกสร้างขึ้นเรียบร้อยแล้ว");
} catch (err) {
next(err);
}
};
export const login = async (req, res, next) => {
try {
const user = await User.findOne({ username: req.body.username });
if (!user) return next(createError(404, "ไม่พบผุ้ใช้งานนี่"));
const isPasswordCorrect = await bcrypt.compare(
req.body.password,
user.password
);
if (!isPasswordCorrect) return next(createError(404, "รหัสผ่านไม่ถูกต้อง"));
//สร้าง key จาก openssl
const token = jwt.sign({ id: user._id, isAdmin: user.isAdmin }, process.env.JWT);
const { password, isAdmin, ...otherDetails } = user._doc;
//เก็บค่า cookie
res.cookie("access_token", token, {
httpOnly: true,
}).status(200).json({ otherDetails });
} catch (err) {
next(err);
}
};
|
/*
* File: 5-free_dog.c
* Author: salem676
*/
#include <stdio.h>
#include <stdlib.h>
#include "dog.h"
/**
* free_dog - function that frees dogs.
* @d: pointer argument passed from main.
* Description: function that frees dogs.
* Return: void.
*/
void free_dog(dog_t *d)
{
if (d != NULL)
{
free(d->owner);
free(d->name);
free(d);
}
}
|
# How to Use
To use this React To Do App, follow these steps:
1. **Clone the Repository**: Start by cloning this repository to your local machine using the following command:
```bash
git clone https://github.com/Josh-techie/React-ODC
```
2. **Navigate to the Project Directory**: Move into the project directory:
```bash
cd React-ODC
```
3. **Install Dependencies**: Make sure you have Node.js and npm (Node Package Manager) installed. Then, install the project dependencies:
```bash
npm install
```
4. **Start Vite**: In the project directory, start Vite to launch the app:
```bash
npm run dev
```
5. **View the App**: Open your web browser and visit http://localhost:3000 to view and use the To Do App.
- That's it! You now have the To Do App up and running locally on your machine using Vite. You can add, complete, and manage your tasks easily using this intuitive app.
### Happy task managing! 🎈

## About:
- This is based on a 3 days course titled: ***ReactJS*** from Orange ODC
## Features
- **Add Tasks**: Easily add new tasks to your to-do list. Simply enter task descriptions in the input field and click "Add."
- **Toggle Completion**: Check off completed tasks with a simple click, with a clear visual cue.
- **Delete Tasks**: Remove tasks effortlessly by hitting the "Delete" button.
- **Task Count**: Always know how many tasks you have left to conquer.
- **Visual Feedback**: Completed tasks stand out with a neat line-through effect.
- **User-Friendly Design**: Enjoy a responsive and visually appealing interface for a smooth task management experience.
The To Do App simplifies your daily tasks, from chores to work assignments, helping you conquer your day with ease.

## Testing Features
### Add Task


### Task Completed:

### Task Uncompleted:
- Click Undo, or click on the radio button:

### Task Edited:
- Click on edit, and then:

- Then you either save your edit, or cancel:
- Let's save and see:

- Let's edit and then cancel:

- After cancel:

- Still the same old task yaaay 😁
### Task Deleted:
- **The order here is:**
- 1. Grocery
- 2. Stretching

- When you delete the task 1 (*Grocery*), the count is self-rendered and the now task (*Stretching*) is labeled as number 1.

## Author:
- Youssef Abouyahia: [Josh-techie](https://github.com/Josh-techie)
### See you next time, happy coding 😋

|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSkillItemsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('skillitems', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('language_id')->unsigned()->nullable();
$table->foreign('language_id')->references('id')->on('languages')->onDelete('set null');
$table->integer('skillset_id')->unsigned()->nullable();
$table->foreign('skillset_id')->references('id')->on('skillsets')->onDelete('set null');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('skillitems');
}
}
|
算法部署:
预准备:
1.部署的脚本,以函数的形式。
脚本要导入的包(无需本地安装,服务器上要安装):
from socketserver import ThreadingMixIn
from xmlrpc.server import SimpleXMLRPCServer
脚本尾部添加的代码:
#一个永远驻扎的程序
if __name__ == '__main__':
#s = SimpleXMLRPCServer(('0.0.0.0', 8003))
s = ThreadXMLRPCServer(('0.0.0.0', 8004)) # 参数 8004:公司提供的端口
print("Listening on port 8004") # 用于测试是否部署成功
#s.register_function(main1)
s.register_function(user_identity) # 注册的函数名,即函数接口,脚本提供给外不的接口
#s.register_function(FileFenci.chuli)
#s.register_function(result_json)
#s.register_function(read_file)
s.serve_forever()
2.Xmanager安装:
安装xmannager
账号/密码:root/Zaq12wsx! IP:119.3.4.18
登陆后:可在该环境下上转脚本及用到的文件:例如训练好的模型(当时遇到一个问题:编译时提醒没有sklearn模块,
是因为虚拟机环境没有安装该模块)
关于部署:
安装xmanager后,
1.打开xshell:
######################################################################
# Notice #
# #
# 1. Please create unique passwords that use a combination of words,#
# numbers, symbols, and both upper-case and lower-case letters. #
# Avoid using simple adjacent keyboard combinations such as #
# "Qwert!234","Qaz2wsx",etc. #
# #
# 2. Unless necessary, please DO NOT open or use high-risk ports, #
# such as Telnet-23, FTP-20/21, NTP-123(UDP), RDP-3389, #
# SSH/SFTP-22, Mysql-3306, SQL-1433,etc. #
# #
# #
# Any questions please contact 4000-955-988 #
######################################################################
[root@ecs-03-01-0005 ~]#
2.如上显示后:键入:cd .. ,返回上一级目录:
键入:ls ,即可看到mengy文件夹
键入:cd mengyi 即可看到mengyi文件夹下的子目录,每个子目录表示一种功能的算法
3. 如需部署新算法,新建之目录:mkdir new_algorithm,把需要的文件和脚本导入
nohup python3 new_alg.py 编译部署程序
ps -ef|grep python 查看现有部署的程序
kill -9 端口号 :杀掉部署的程序
4. 测试算法部署脚本:
# -*- coding: utf-8 -*-
import xmlrpc.client
import json
data = {
"uuid": "465fff2b94314ee0a533d270deddc8fd",
"ram": "887.000000",
"accessApp": "FaceCheck",
"accessTime": "2018-11-06 15:28:35",
"appType": "iOS",
"brand": "苹果",
"city": "上海市",
"country": "中国",
"cpu": "{\r\n \"cpuNumber\" : \"2\",\r\n \"cpuName\" : \"Apple A8\",\r\n \"cpuType\" : \"CPU_TYPE_ARM64\"\r\n}",
"deviceType": "iPhone 6",
"diskSpace": "14.89 GB",
"ip": "172.16.20.142",
"isEmulator": "0",
"isJailbreak": "0",
"isProxy": "0",
"isRoot": "0",
"isVm": "0",
"isVpn": "0",
"location": "{\n \"longitude\" : \"120.102138\",\n \"latitude\" : \"30.301264\"\n}",
"networkType": 'Wi-Fi',
"operatorSystem": "iOS",
"os": "iOS",
"osVersion": 11,
"platform": "iPhone 6",
"region": "浙江省",
"resolution": "逻辑:667 × 375; 物理:1334 × 750",
"screenDpi": "逻辑:667 × 375; 物理:1334 × 750",
"screenSize": "逻辑:667 × 375; 物理:1334 × 750",
"shellSize": "逻辑:667 × 375; 物理:1334 × 750",
"wifiSsid": "{\r\n \"wifiBssid\" : \"5c:3c:60:77:d5:50\",\r\n \"wifiSignalStrength\" : \"3\",\r\n \"wifiSsid\" : \"Powecn-All\",\r\n \"currentIP\" : \"172.16.20.142\",\r\n \"CarrierInfo\" : \"\",\r\n \"wifiName\" : \"Powecn-All\"\r\n}",
"createTime": "2018-11-06 15:28:06.0",
"updateTime": "2018-11-08 14:40:36.0"
}
# create object
s = xmlrpc.client.ServerProxy('http://119.3.4.18:8004') # 服务的ip及端口号,并生产一个对象
# print user id
uid = s.user_identity(data) # user_identity 注册的函数,data:函数需要传入的参数
print(uid) # 如果打印出预想的结果说明部署成功
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('username')->unique();
$table->string('address')->nullable();
$table->string('phone')->nullable();
$table->string('bio')->nullable();
$table->string('email')->unique();
$table->string('password')->nullable();
$table->string('avatar')->nullable();
$table->boolean('blocked')->default(false);
$table->boolean('formalities')->default(false);
$table->rememberToken();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
|
import { ReloadIcon } from "@radix-ui/react-icons";
import { useQuery } from "@tanstack/react-query";
import { useAtom, useAtomValue } from "jotai";
import { isEmpty, isEqual } from "lodash-es";
import React, { Suspense } from "react";
import { match } from "ts-pattern";
import { DefaultService } from "../../client";
import { availableInterventionsAtom, paramsAtom } from "../../stores/atoms";
import {
baseInterventionAtom,
customInterventionAtom,
interventionAtom,
} from "../../stores/report";
import { groupInterventions } from "../../utils/interventionAreas";
import Markdown from "../../components/Markdown";
import { sort } from "d3";
import { ErrorBoundary } from "../../components/support/ErrorHandling";
import { LoadingFallback } from "../../components/support/LoadingFallback";
import { CustomizationNote } from "../interventions/CustomizationNote";
import { DALYsPer1000 } from "../interventions/DALYsPer1000";
import { ResultSummary } from "../interventions/ResultSummary";
import { InterventionConfiguration as AnimalInterventionConfiguration } from "../interventions/animalWelfare/InterventionConfiguration";
import { InterventionConfiguration as GhdInterventionConfiguration } from "../interventions/ghd/InterventionConfiguration";
import { InterventionConfiguration as XRiskInterventionConfiguration } from "../interventions/xRisk/InterventionConfiguration";
import { AlternativesComparison } from "../../components/plots/AlternativesComparison";
import { ConfigurabilityMessage } from "../../components/ConfigurabilityMessage";
export function Interventions() {
return (
<section>
<h2 id="interventions">Interventions</h2>
<p>
Interventions are projects that directly aim to make the world a better
place, and they form the most important abstraction in CCM. The CCM
assesses intervention cost-effectiveness in the amount of{" "}
<a href="https://en.wikipedia.org/wiki/Disability-adjusted_life_year">
Disability Adjusted Life Years (DALYs)
</a>{" "}
averted per $1000 invested in the intervention.
</p>
<p>
A DALY is a unit of value tied to a degree of human misfortune, which is
widely used in global health and development research. We expand the
traditional definition of a DALY by valuing animals and lost future
lives by performing customizable conversions to their equivalent in
human DALYs.
</p>
<p>
The CCM provides preset interventions: template models for interventions
in different cause areas. Each preset comes with some default
assumptions. Real-world projects inspire some of these default
assumptions, while others are arbitrary or represent our best guesses.
We expect users to customize these assumptions as needed.
</p>
<p>
Once you select an intervention, the CCM will take the assumptions,
which are encoded as probability distributions, and sample them
thousands of times to provide the final distribution of results.
It's important to note that this only provides a rough probability
assessment, and this can also lead to highly erratic results for
interventions that are highly sensitive to long-shot outcomes (like
existential risk interventions).
</p>
<p>Select a preset intervention to get started:</p>
<ErrorBoundary>
<SelectIntervention />
<Intervention />
</ErrorBoundary>
</section>
);
}
function SelectIntervention() {
// Available interventions
const availableInterventions = useAtomValue(
availableInterventionsAtom,
).filter((intervention) => intervention.area != "not-an-intervention");
const [baseIntervention, setBaseIntervention] = useAtom(baseInterventionAtom);
const [customIntervention, setCustomIntervention] = useAtom(
customInterventionAtom,
);
const intervention = customIntervention ?? baseIntervention;
const interventionsByArea = groupInterventions(availableInterventions);
return (
<div>
<select
className="mb-4 block w-full rounded select select-bordered"
name="intervention-preset"
onChange={(e) => {
const newIntervention = availableInterventions.find(
(intervention) => intervention.name == e.target.value,
);
setBaseIntervention(newIntervention);
setCustomIntervention(newIntervention);
}}
value={intervention?.name}
>
<option>Select an intervention</option>
{interventionsByArea.map(
({ area: group, interventions: interventions }) => {
if (group === "Utility") return null;
return (
<optgroup key={group} label={group}>
{interventions.map((intervention) => (
<option key={intervention.name} value={intervention.name}>
{intervention.name}
</option>
))}
</optgroup>
);
},
)}
</select>
</div>
);
}
export function Intervention() {
const baseIntervention = useAtomValue(baseInterventionAtom);
const [customIntervention, setCustomIntervention] = useAtom(
customInterventionAtom,
);
const [allParams, setAllParams] = useAtom(paramsAtom);
const isCustomized =
!isEqual(customIntervention, baseIntervention) ||
!Object.values(allParams).every((areaParams) => isEmpty(areaParams));
const resetSettings = () => {
setAllParams({});
setCustomIntervention(baseIntervention);
};
return (
<>
{baseIntervention && (
<div>
<Suspense fallback={<LoadingFallback />}>
{isCustomized && <CustomizationNote triggerReset={resetSettings} />}
{!isCustomized && <ConfigurabilityMessage />}
<InterventionDescription />
<InterventionConfiguration />
</Suspense>
<Suspense fallback={<LoadingFallback />}>
<InterventionAssessment />
</Suspense>
</div>
)}
</>
);
}
function InterventionDescription() {
const intervention = useAtomValue(interventionAtom);
if (!intervention) return null;
return (
<div>
<h3>{intervention.name}</h3>
<Markdown>{intervention.description}</Markdown>
</div>
);
}
export function InterventionConfiguration() {
const intervention = useAtomValue(interventionAtom);
if (!intervention) return null;
return (
<Suspense fallback={<LoadingFallback />}>
{match(intervention.area)
.returnType<React.ReactNode>()
.with("ghd", () => <GhdInterventionConfiguration />)
.with("animal-welfare", () => <AnimalInterventionConfiguration />)
.with("xrisk", () => <XRiskInterventionConfiguration />)
.otherwise(() => (
<div></div>
))}
</Suspense>
);
}
export const InterventionAssessment = () => {
const parameters = useAtomValue(paramsAtom);
const intervention = useAtomValue(interventionAtom)!;
const { data, isRefetching, refetch } = useQuery({
queryKey: ["interventionAssesment", intervention, parameters],
queryFn: () =>
DefaultService.estimateInterventionDalys(intervention.name, {
intervention: intervention,
parameters: parameters,
}),
});
const orderedSamples = {
samples: sort(data?.samples ?? []),
num_zeros: data?.num_zeros ?? 0,
};
if (isRefetching) return <LoadingFallback />;
return (
<Suspense fallback={<LoadingFallback />}>
<ErrorBoundary>
<h3 className="mt-[2em]" id="simulation-results">
Simulation Results
<ReloadIcon
height="1em"
width="1em"
className="ml-2 cursor-pointer align-middle"
onClick={() => {
void refetch();
}}
/>
</h3>
<ResultSummary results={orderedSamples} includeWaffleChart={true} />
<DALYsPer1000 interventionSamples={orderedSamples} />
<AlternativesComparison
values={orderedSamples}
unit="DALYs per $1000"
/>
</ErrorBoundary>
</Suspense>
);
};
|
import mongoose from "mongoose";
const MessageFactory = (connectedMongoose) => {
const MessageSchema = new connectedMongoose.Schema({
text: { type: String },
donorEmail: {
type: mongoose.Types.ObjectId,
ref: "PersonWithEmail",
required: true,
},
interestedPartyEmail: {
type: mongoose.Types.ObjectId,
ref: "PersonWithEmail",
required: true,
},
paintId: {
type: mongoose.Types.ObjectId,
ref: "PaintCan",
required: true,
},
postedOn: { type: Date, required: false, default: Date.now },
sent: { type: Boolean, required: false, default: false },
});
const MessageModel = connectedMongoose.model(
"MessageSchema",
MessageSchema,
"message"
);
return {
MessageSchema,
MessageModel,
};
};
export default MessageFactory;
|
import jwt from "jsonwebtoken";
import asyncHandler from "express-async-handler";
import User from "../Models/userModel.js";
const protect = asyncHandler(async (req, res, next) => {
let token;
token = req.cookies.Userjwt;
if (token) {
try {
const decoded = jwt.verify(token, process.env.JWT_CODE);
const user = await User.findById(decoded.userId).select("-password");
if (!user) {
res.status(403);
return res.json({ success: false, message: "Not authorized, user not found" });
}
if (user.isBlocked === true) {
res.status(403);
return res.json({ success: false, message: "User is blocked" });
}
// Check user roles
if (user.roles.includes('user')) {
// Grant access for users with the 'user' role only
req.user = user;
next();
} else {
res.status(403);
return res.json({ success: false, message: "Not authorized, insufficient role" });
}
} catch (error) {
console.error(error);
res.status(401);
return res.json({ success: false, message: "Not authorized, token failed" });
}
} else {
res.status(401);
return res.json({ success: false, message: "Not authorized, no token" });
}
});
export { protect };
|
<template>
<form @submit.prevent="formSubmit">
<div class="flex flex-row justify-start items-center">
<TextInput class="flex-grow mr-2 w-32" id="search" type="text" v-model="form.q" autocomplete="search"
placeholder="Поиск" />
<select class="rounded-md mr-2" v-model="form.grade">
<option value="">Все классы</option>
<option v-for="(gradeTitle, gradeValue) in gradeValues" :value="gradeValue">
{{ gradeTitle }}
</option>
</select>
<PrimaryButton>
<SearchIcon />
</PrimaryButton>
</div>
</form>
</template>
<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import TextInput from '@/Components/TextInput.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import SearchIcon from '@/Components/Icons/SearchIcon.vue';
const gradeValues = {
5: '5 класс',
6: '6 класс',
7: '7 класс',
8: '8 класс',
9: '9 класс',
10: '10 класс',
11: '11 класс',
};
const form = useForm({
q: '',
grade: '',
});
function formSubmit() {
form.get(route('admin.learning_materials.index'), {
preserveState: true,
});
}
</script>
|
package controller
import (
"encoding/json" // package untuk enkode dan mendekode json menjadi struct dan sebaliknya
"fmt"
"strconv" // package yang digunakan untuk mengubah string menjadi tipe int
"sync"
"log"
"net/http" // digunakan untuk mengakses objek permintaan dan respons dari api
"go-postgres-crud/models" //models package dimana Buku didefinisikan
"github.com/gorilla/mux" // digunakan untuk mendapatkan parameter dari router
_ "github.com/lib/pq" // postgres golang driver
)
type response struct {
ID int64 `json:"id,omitempty"`
Message string `json:"message,omitempty"`
}
type Payload struct {
Data []struct {
Page int `json:"page"`
Content string `json:"content"`
} `json:"data"`
}
type Response struct {
Status int `json:"status"`
Message string `json:"message"`
Data []models.Book `json:"data"`
}
type ResponseData struct {
Message string `json:"message"`
Data []string `json:"data"`
}
// AddBook
func AddBook(w http.ResponseWriter, r *http.Request) {
var book models.Book
err := json.NewDecoder(r.Body).Decode(&book)
if err != nil {
log.Fatalf("error encode body. %v", err)
}
insertID := models.AddBook(book)
res := response{
ID: insertID,
Message: "Success add Book",
}
json.NewEncoder(w).Encode(res)
}
// AddBook
func AddPageValidation(w http.ResponseWriter, r *http.Request) {
var payload Payload
var data []string
var wg sync.WaitGroup
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
fmt.Println(err)
return
}
for _, d := range payload.Data {
wg.Add(1)
go func(index string) {
defer wg.Done()
data = append(data, index)
}(d.Content)
}
wg.Wait()
res := ResponseData{
Message: "Success",
Data: data,
}
json.NewEncoder(w).Encode(res)
}
func GetBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Context-Type", "application/x-www-form-urlencoded")
w.Header().Set("Access-Control-Allow-Origin", "*")
params := mux.Vars(r)
id, err := strconv.Atoi(params["id"])
if err != nil {
log.Fatalf("Invalid Format ID. %v", err)
}
book, err := models.GetBook(int64(id))
if err != nil {
log.Fatalf("Failed Get Data. %v", err)
}
json.NewEncoder(w).Encode(book)
}
func GetAllBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Context-Type", "application/x-www-form-urlencoded")
w.Header().Set("Access-Control-Allow-Origin", "*")
title := r.URL.Query().Get("title")
books, err := models.GetAllBook(string(title))
if err != nil {
log.Fatalf("Failed Get Data. %v", err)
}
var response Response
response.Status = 1
response.Message = "Success"
response.Data = books
json.NewEncoder(w).Encode(response)
}
func UpdateBook(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id, err := strconv.Atoi(params["id"])
if err != nil {
log.Fatalf("Invalid Format ID. %v", err)
}
var book models.Book
err = json.NewDecoder(r.Body).Decode(&book)
if err != nil {
log.Fatalf("error encode body. %v", err)
}
updatedRows := models.UpdateBook(int64(id), book)
msg := fmt.Sprintf("Success Update Data %v rows/record", updatedRows)
res := response{
ID: int64(id),
Message: msg,
}
json.NewEncoder(w).Encode(res)
}
func DeleteBook(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id, err := strconv.Atoi(params["id"])
if err != nil {
log.Fatalf("Invalid Format ID. %v", err)
}
deletedRows := models.DeleteBook(int64(id))
msg := fmt.Sprintf("Success Delete Data %v", deletedRows)
res := response{
ID: int64(id),
Message: msg,
}
json.NewEncoder(w).Encode(res)
}
|
import { formatEpisodeCode } from "./formatEpisodeCode";
import { cleanUpSummary } from "./cleanUpSummary";
export interface IEpisode {
id: number;
url: string;
name: string;
season: number;
number: number;
type: string;
airdate: string;
airtime: string;
airstamp: string;
rating: { average: number | null };
runtime: number;
image: null | {
medium: string;
original: string;
};
summary: string | null;
_links: { self: { href: string } };
}
interface EpisodeViewProp {
episode: IEpisode;
}
export function DisplayEpisode(props: EpisodeViewProp): JSX.Element {
return (
<div className="episode">
<p className="episodeName">{props.episode.name}</p>
<p className="episodeCode">
{formatEpisodeCode(props.episode.season, props.episode.number)}
</p>
<hr className="dividerLine"></hr>
<div>
{props.episode.image && (
<img
className="episodeImg"
src={props.episode.image.medium}
alt="props.episode.name"
/>
)}
</div>
{props.episode.summary && (
<p className="episodeSummary">
{cleanUpSummary(props.episode.summary)}
</p>
)}
</div>
);
}
|
import React from 'react';
import {View, StyleSheet, Text} from 'react-native';
import {colors, sizes, spacing} from '../constants/theme';
import FavoriteButton from './ui/FavoriteButton';
import {useNavigation} from '@react-navigation/native';
import {SharedElement} from 'react-navigation-shared-element';
import Card from './Card/Card';
import CardMedia from './Card/CardMedia';
import CardContent from './Card/CardContent';
import { Screens } from '../navigation/screens/Screens';
const CARD_WIDTH = sizes.width / 2 - (spacing.l + spacing.l / 2);
const CARD_HEIGHT = 220;
const TripsList = ({list}) => {
const navigation = useNavigation();
return (
<View style={styles.container}>
{list.map((item, index) => {
return (
<Card
key={item.id}
style={styles.card}
onPress={() => {
navigation.navigate(Screens.TRIPDETAILS, {trip: item});
}}>
<SharedElement id={`trip.${item.id}.image`} style={styles.media}>
<CardMedia source={item.image} />
</SharedElement>
<CardContent style={styles.content}>
<View style={styles.titleBox}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.location}>{item.location}</Text>
</View>
<FavoriteButton />
</CardContent>
</Card>
);
})}
</View>
);
};
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
flexWrap: 'wrap',
},
cardContainer: {
marginLeft: spacing.l,
marginBottom: spacing.l,
},
card: {
width: CARD_WIDTH,
height: CARD_HEIGHT,
marginLeft: spacing.l,
marginBottom: spacing.l,
},
media: {
flex: 1,
},
content: {
paddingRight: spacing.m / 2,
},
titleBox: {
flex: 1,
},
title: {
marginVertical: 4,
fontSize: sizes.body,
fontWeight: 'bold',
color: colors.primary,
},
location: {
fontSize: sizes.body,
color: colors.lightGray,
},
});
export default TripsList;
|
<?php
namespace App\Http\Controllers;
use App\Models\Note;
use Illuminate\Http\Request;
class NoteController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$title = 'Заметки';
$notes = Note::orderBy('id', 'DESC')->get();
return view('index', compact('title', 'notes'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
$title = 'Добваить заметку';
return view('create', compact('title'));
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
if (!$request->ajax()) {
abort(404);
}
$request->validate([
'title' => 'required|min:2',
'content' => 'required|min:5',
]);
$note = $request->all();
$noteCopy = Note::create($note);
return $noteCopy;
}
/**
* Display the specified resource.
*/
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
$note = Note::find($id);
if (!$note) {
return abort(404);
}
$title = 'Изменит заметку' . $note->title;
return view('edit', compact('title', 'note'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
$request->validate([
'title' => 'required|min:2',
'content' => 'required|min:5',
]);
$note = Note::find($id);
$data = $request->all();
$note->update($data);
return redirect()->route('home');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
Note::destroy($id);
return redirect()->route('home');
}
}
|
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>
浅谈拓扑(五)
</title>
<link rel="stylesheet" type="text/css" href="print.css" media="print">
<style type="text/css">
.background-image{text-align: center;max-width: inherit;}.background-image img{max-width: 100%;}.video{max-width: inherit;margin: 80px auto;}.video-cover{max-width: inherit;background-color: #141216;}.video img{height: 400px;display: block;margin: 0 auto;}.video-tip{border-radius: 0 0 8px 8px;max-width: inherit;height: 34px;text-align: center;}.header{margin-bottom: 80px;}.title{font-size: 36px;margin-bottom: 80px;text-align: center;line-height: 42px;}.AuthorInfo,.Avatar{border-radius: 5px;}.Popover{width: 50px;height: 50px;}.AuthorInfo{width: 240px;margin: auto;}.AuthorInfo-content{position: relative;left: 60px;top: -50px;line-height: 1em;padding: 6px 0;}.AuthorInfo-name{font-size: 28px;}.AuthorInfo-detail{font-size: 16px;margin-top: 8px;}.Popover,.AuthorInfo,.AuthorInfo-content,.AuthorInfo{height: 50px;}.LinkCard{margin: 1em auto;width: 390px !important;border-radius: 12px;}.LinkCard-content{position: relative;display: -webkit-box;display: -ms-flexbox;display: flex;-webkit-box-align: center;-ms-flex-align: center;align-items: center;-webkit-box-pack: justify;-ms-flex-pack: justify;justify-content: space-between;padding: 12px;border-radius: inherit;background-color: hsla(0, 0%, 96.5%, 0.88);}.LinkCard-text{overflow: hidden;}.LinkCard-title{display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;overflow: hidden;text-overflow: ellipsis;max-height: 40px;font-size: 16px;font-weight: 500;line-height: 1.25;color: #1a1a1a;}.LinkCard-meta{display: -webkit-box;display: -ms-flexbox;display: flex;margin-top: 4px;font-size: 14px;line-height: 20px;color: #999;white-space: nowrap;}.LinkCard-imageCell{margin-left: 8px;border-radius: 6px;}.LinkCard-image{display: block;margin: 0 !important;width: 60px;height: 60px;-o-object-fit: cover;object-fit: cover;border-radius: inherit;}.LinkCard-image--default{display: -webkit-box;display: -ms-flexbox;display: flex;-webkit-box-align: center;-ms-flex-align: center;align-items: center;-webkit-box-pack: center;-ms-flex-pack: center;justify-content: center;background-color: #ebebeb;color: #d3d3d3;}svg:not(:root){overflow: hidden;}.TipCard,.LinkCard{position: relative;display: block;width: inherit;-webkit-box-sizing: border-box;box-sizing: border-box;max-width: 100%;overflow: hidden;text-indent: 0 !important;}.TipCard,.LinkCard,.TipCard:hover,.LinkCard:hover{text-decoration: none;border: none !important;color: inherit !important;}.TipCard-backdrop,.LinkCard-backdrop{position: absolute;top: 0;left: 0;right: 0;bottom: 0;background-repeat: no-repeat;-webkit-filter: blur(20px);filter: blur(20px);background-size: cover;background-position: 50%;}.divide{height: 30px;max-width: 45em;margin: 0 auto;}.reference{text-indent: 0;font-size: 14px;}.reference tr:nth-child(2n){background: white;}
</style>
<style type="text/css">
*,::after,::before{box-sizing: border-box;}body{font-size: 1.2rem;line-height: 1.5em;background-color: #f6f6f6;font-family: "PT Serif", "Times New Roman", Times, serif, "Helvetica Neue", Helvetica, Arial, sans-serif;color: rgb(31, 9, 9);}.article{max-width: 50em;margin: 0px auto;padding: 6em;background: #fff;overflow: hidden;border-radius: 2px;-webkit-box-shadow: 0 1px 3px rgba(26, 26, 26, 0.1);box-shadow: 0 1px 3px rgba(26, 26, 26, 0.1);-webkit-box-sizing: border-box;box-sizing: border-box;}p{margin-bottom: 1.5em;line-height: inherit;}p img[eeimg]{display: inline-block;margin: 0 3px;max-width: 100%;vertical-align: middle;}p + ul,p + ol{margin-top: 0.5em;}blockquote{margin: 0 2em;background: #eee;border-radius: 5px;padding: 15px;color: rgb(101, 101, 101);font-style: italic;}blockquote p{background: #eee;border-radius: 5px;}blockquote p::before{content: "\201C";}blockquote p::after{content: "\201D";}blockquote ul,blockquote ol{margin-left: 0px;}blockquote::before,blockquote::after,q::before,q::after{content: none;}blockquote > :first-child,li > :first-child{margin-top: 0px;}blockquote > :last-child{margin-bottom: 0px;}blockquote,q{quotes: none;}a{cursor: pointer;text-decoration: none;color: #3ac19f;}a:hover,a:active{text-decoration: none;color: #ff6188;outline: 0px;}a.url{word-break: break-all;}table tr th{border-bottom: 0px;}table{border-collapse: collapse;border-spacing: 0px;margin-bottom: 1.5em;font-size: 1em;width: 100%;overflow: auto;break-inside: auto;text-align: left;}header,footer{font-family: "PT Serif", "Times New Roman", Times, serif;color: rgb(31, 9, 9);}thead{background-color: rgb(218, 218, 218);display: table-header-group;}thead th,tfoot th{padding: 0.25em 0.25em 0.25em 0.4em;text-transform: uppercase;}tr{break-inside: avoid;break-after: auto;}tr:nth-child(2n){background: rgb(232, 231, 231);}th{text-align: left;}td{vertical-align: top;padding: 0.25em 0.25em 0.25em 0.4em;}tt{font-size: 0.8em;line-height: 1.7em;}ol,ul{text-indent: 0;position: relative;list-style: none;margin: 0px 0px 1.5em 1.5em;}ol li{list-style-type: decimal;list-style-position: outside;}ul li{list-style-type: disc;list-style-position: outside;}li div{padding-top: 0px;}li{margin: 0px;margin-left: 2em;position: relative;}li > figure:last-child{margin-bottom: 0.5rem;}li > :first-child{margin-top: 0px;}li > ul,li > ol{margin-top: inherit;margin-bottom: 0px;}li ol > li{list-style-type: lower-alpha;}li li ol > li{list-style-type: lower-roman;}kbd{margin: 0px 0.1em;padding: 0.1em 0.6em;font-size: 0.8em;color: rgb(36, 39, 41);background: rgb(255, 255, 255);border: 1px solid rgb(173, 179, 185);border-radius: 3px;box-shadow: rgba(12, 13, 14, 0.2) 0px 1px 0px,rgb(255, 255, 255) 0px 0px 0px 2px inset;white-space: nowrap;vertical-align: middle;}samp,tt{font-family: var(--monospace);}hr{border-bottom: 1px solid #d6d6d6;margin-inline-start: 15%;margin-inline-end: 15%;margin-block-start: 5rem;margin-block-end: 5rem;}u{text-decoration: none;border-bottom: 1px dashed #f40;}figure{margin: 2em auto;max-width: 100%;padding: 0px;font-size: 1rem;text-align: center;}figure img{display: block;max-width: 60%;margin: auto;}figure figcaption{padding: 0 1em;font-size: 0.9rem;color: #999;}figure > table{margin: 0px !important;}div.hr:focus{cursor: none;}a img,img a{cursor: pointer;}
</style>
</head>
<body>
<div class="article">
<div class="header">
<div class="background-image">
<img src="https://pic3.zhimg.com/v2-e4269b572c79908da19ddd47c56ea544_720w.jpg?source=172ae18b" alt="background image">
</div>
<div class="title">
<a href="https://zhuanlan.zhihu.com/p/104525216" target="_blank">
浅谈拓扑(五)
</a>
</div>
<a class="UserLink-link" target="_blank" href="https://www.zhihu.com/people/zhou-hao-cheng-30">
<div class="AuthorInfo">
<div class="Popover">
<img class="Avatar" width="50" height="50" src="https://pic1.zhimg.com/v2-53d7fc04a71ec457c22be74dc42c7b09.jpg?source=172ae18b" alt="头像">
</div>
<div class="AuthorInfo-content">
<div class="AuthorInfo-name">
<span>
sola
</span>
</div>
<div class="AuthorInfo-detail">
<span>
2020-01-31
</span>
</div>
</div>
</div>
</a>
</div>
<div class="text">
<p>
其实我最近的更新用了很多“清凉”的图片是有原因的。这些图都是夏天的时候抠的,当时想着多写点东西,可惜未能如愿。想着放着也是放着,不如拿出来当封面,所以就干脆直接用啦|ू・ω・` )
</p>
<p>
希望大家不要对封面有啥误会呀,当成是欣赏艺术就行了。反正数学也是一种艺术,从这种意味上来看还是挺合适的(并不。因为误会点进来的读者也可以读一读再放弃治疗,万一对数学还挺有兴趣的呢是不哈哈。
</p>
<p>
<br>
</p>
<p>
<br>
</p>
<p>
我们进入正题,来说说上次落下的
<b>
可数性公理
</b>
。
</p>
<p>
<b>
C1公理:任意拓扑空间中的点都具有可数邻域基。
</b>
</p>
<p>
<b>
C2公理:拓扑空间具有可数拓扑基。
</b>
</p>
<p>
<br>
</p>
<p>
在这里,我们有必要解释一下邻域基是什么。
</p>
<p>
取定一点
<img src="https://www.zhihu.com/equation?tex=x%5Cin+X" alt="x\in X" eeimg="1">
,如果
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的若干个邻域能够组成一个集合,使得任意
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的邻域
<img src="https://www.zhihu.com/equation?tex=W" alt="W" eeimg="1">
,总是能够找到这个集合中的某个元素
<img src="https://www.zhihu.com/equation?tex=U" alt="U" eeimg="1">
,使得
<img src="https://www.zhihu.com/equation?tex=U%5Csubset+W" alt="U\subset W" eeimg="1">
,那么这个集合就称为点
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
处的一组
<b>
邻域基
</b>
。
</p>
<p>
回忆一下拓扑基的定义:
</p>
<p>
对任意开集
<img src="https://www.zhihu.com/equation?tex=W" alt="W" eeimg="1">
,如果都存在集合中元素
<img src="https://www.zhihu.com/equation?tex=U" alt="U" eeimg="1">
,使得
<img src="https://www.zhihu.com/equation?tex=U%5Csubset+W" alt="U\subset W" eeimg="1">
,那么这个集合就被称为一组拓扑基。
</p>
<p>
很相似吧!
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的邻域基中的元素事实上都是“最本原的”邻域,类比于拓扑基的定义。
</p>
<p>
<br>
</p>
<p>
<br>
</p>
<p>
<b>
关于C1公理:
</b>
</p>
<p>
我们最熟悉的欧氏拓扑
<img src="https://www.zhihu.com/equation?tex=%5Cmathbb%7BE%7D%5E1" alt="\mathbb{E}^1" eeimg="1">
自然是C1的,因为对于任意实数
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
,
<img src="https://www.zhihu.com/equation?tex=%5Cleft+%5C%7B+B%28x%2C%5Cdelta%29+%7C%5Cdelta%5Cin%5Cmathbb%7BQ%7D%5Cright+%5C%7D" alt="\left \{ B(x,\delta) |\delta\in\mathbb{Q}\right \}" eeimg="1">
都是一组邻域基(有理数的稠密性),显然是可数的。
</p>
<p>
理解C1公理的含义并不是一件容易的事,但是我们可以慢慢深入理解。
</p>
<p>
首先,注意到在任意点
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
处的可数邻域基本质上也都是
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的邻域。假设邻域基为
<img src="https://www.zhihu.com/equation?tex=%5Cleft+%5C%7B++U_1%2CU_2%2C...%5Cright+%5C%7D" alt="\left \{ U_1,U_2,...\right \}" eeimg="1">
,那么我们可以稍做变换:
</p>
<p>
令
<img src="https://www.zhihu.com/equation?tex=V_1%3DU_1%2CV_2%3DU_1%5Ccap+U_2%2C...%2CV_n%3DU_1%5Ccap...%5Ccap+U_n%2C..." alt="V_1=U_1,V_2=U_1\cap U_2,...,V_n=U_1\cap...\cap U_n,..." eeimg="1">
</p>
<p>
我们立马发现:
<img src="https://www.zhihu.com/equation?tex=%5Cleft+%5C%7B++V_n%5Cright+%5C%7D" alt="\left \{ V_n\right \}" eeimg="1">
是一个单调递减的集合列,且列中每个元素都仍为
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的邻域。
</p>
<p>
利用邻域基的性质,对于任意
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的邻域
<img src="https://www.zhihu.com/equation?tex=W" alt="W" eeimg="1">
,存在
<img src="https://www.zhihu.com/equation?tex=U_n%2CU_n%5Csubset+W" alt="U_n,U_n\subset W" eeimg="1">
</p>
<p>
那么也就有
<img src="https://www.zhihu.com/equation?tex=V_n%5Csubset+W" alt="V_n\subset W" eeimg="1">
。得到:
<img src="https://www.zhihu.com/equation?tex=%5Cleft+%5C%7B++V_n%5Cright+%5C%7D" alt="\left \{ V_n\right \}" eeimg="1">
为
<b>
一组单调递减的邻域基
</b>
。(C1公理的等价条件)
</p>
<p>
<br>
</p>
<p>
<br>
</p>
<p>
由单调递减的一组
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
邻域,我们不难联想到序列的收敛性。是否可以附加一些条件,使得
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
可以被一个序列逼近呢?
</p>
<p>
当
<img src="https://www.zhihu.com/equation?tex=x%5Cin+%5Coverline%7BA%7D" alt="x\in \overline{A}" eeimg="1">
时,其中
<img src="https://www.zhihu.com/equation?tex=A" alt="A" eeimg="1">
为拓扑空间的子集,由聚点定义,任意
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的领域
<img src="https://www.zhihu.com/equation?tex=V_n" alt="V_n" eeimg="1">
,
<img src="https://www.zhihu.com/equation?tex=%28V_n-%5Cleft+%5C%7B+x+%5Cright+%5C%7D%29%5Ccap+A+%5Cneq%5Cvarnothing+" alt="(V_n-\left \{ x \right \})\cap A \neq\varnothing" eeimg="1">
</p>
<p>
这说明我们可以从每个
<img src="https://www.zhihu.com/equation?tex=V_n%5Ccap+A" alt="V_n\cap A" eeimg="1">
中任意取出异于
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的一点
<img src="https://www.zhihu.com/equation?tex=x_n" alt="x_n" eeimg="1">
组成
<img src="https://www.zhihu.com/equation?tex=A" alt="A" eeimg="1">
中的一个序列。
</p>
<p>
对于
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的任意邻域
<img src="https://www.zhihu.com/equation?tex=U" alt="U" eeimg="1">
,总存在
<img src="https://www.zhihu.com/equation?tex=V_n%5Csubset+U" alt="V_n\subset U" eeimg="1">
,故
<img src="https://www.zhihu.com/equation?tex=x_n%2Cx_%7Bn%2B1%7D%2C...%5Cin+U" alt="x_n,x_{n+1},...\in U" eeimg="1">
,即
<img src="https://www.zhihu.com/equation?tex=U" alt="U" eeimg="1">
外总是只有序列
<img src="https://www.zhihu.com/equation?tex=%5Cleft+%5C%7B++x_n%5Cright+%5C%7D" alt="\left \{ x_n\right \}" eeimg="1">
中的有限项,得到
<img src="https://www.zhihu.com/equation?tex=x_n%5Crightarrow+x" alt="x_n\rightarrow x" eeimg="1">
。
</p>
<p>
<br>
</p>
<p>
<b>
C1空间中,若
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
为
<img src="https://www.zhihu.com/equation?tex=A" alt="A" eeimg="1">
的聚点,则必定存在
<img src="https://www.zhihu.com/equation?tex=A" alt="A" eeimg="1">
中序列以
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
为极限!
</b>
这又回到了我们在数学分析中见到的聚点与收敛性之间的联系。事实上,聚点与收敛性的统一是通过C1公理而实现的!
</p>
<p>
事实上由于上述性质,在C1空间中,我们对于
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
处函数
<img src="https://www.zhihu.com/equation?tex=f" alt="f" eeimg="1">
连续性可以利用任意
<img src="https://www.zhihu.com/equation?tex=x_n%5Crightarrow+x" alt="x_n\rightarrow x" eeimg="1">
,都有
<img src="https://www.zhihu.com/equation?tex=f%28x_n%29%5Crightarrow+f%28x%29" alt="f(x_n)\rightarrow f(x)" eeimg="1">
成立来进行判别(与连续性的序列定义吻合)。
</p>
<p>
<br>
</p>
<p>
<br>
</p>
<p>
<b>
关于C2公理:
</b>
</p>
<p>
C2公理可能是比较难以理解的公理,也是比较难以证明的公理。我们都知道欧氏拓扑是C2的,那么不满足C2公理的空间长啥样呢?
</p>
<p>
最简单的例子就是
<b>
实数域上的离散拓扑
</b>
。
</p>
<p>
在离散拓扑中,任意实数域的子集都是开的。我们知道其拓扑基必须包含
<img src="https://www.zhihu.com/equation?tex=%5Cleft+%5C%7B+%5Cleft+%5C%7B++x%5Cright+%5C%7D%7Cx%5Cin+%5Cmathbb%7BR%7D+%5Cright+%5C%7D" alt="\left \{ \left \{ x\right \}|x\in \mathbb{R} \right \}" eeimg="1">
。(否则对于单点集,我们会找不到一个包含在其中的更小开集,这与拓扑基定义矛盾)这个拓扑基显然是不可数的!非C2!
</p>
<p>
<br>
</p>
<p>
再举一个不那么平凡的例子,我们也能够从中学习到证明C2不成立的技巧:
</p>
<p>
考虑实数域上由拓扑基
<img src="https://www.zhihu.com/equation?tex=%5Cmathbb%7BB%7D%3D%5Cleft+%5C%7B++%5Ba%2Cb%29%7Ca%3Cb%2Ca%2Cb%5Cin%5Cmathbb%7BR%7D%5Cright+%5C%7D" alt="\mathbb{B}=\left \{ [a,b)|a<b,a,b\in\mathbb{R}\right \}" eeimg="1">
生成的拓扑。
</p>
<p>
那么
<img src="https://www.zhihu.com/equation?tex=%5Ba%2Ca%2B1%29" alt="[a,a+1)" eeimg="1">
都是开集。若该拓扑有拓扑基
<img src="https://www.zhihu.com/equation?tex=%5Cmathbb%7BA%7D" alt="\mathbb{A}" eeimg="1">
,则存在
<img src="https://www.zhihu.com/equation?tex=U_a%5Cin+%5Cmathbb%7BA%7D" alt="U_a\in \mathbb{A}" eeimg="1">
,使得
<img src="https://www.zhihu.com/equation?tex=a%5Cin+U_a%5Csubset+%5Ba%2Ca%2B1%29" alt="a\in U_a\subset [a,a+1)" eeimg="1">
。注意到在这里
<img src="https://www.zhihu.com/equation?tex=U_a" alt="U_a" eeimg="1">
自身也为开集,故其必定以
<img src="https://www.zhihu.com/equation?tex=a" alt="a" eeimg="1">
作为集合的最小元。
</p>
<p>
只需要考虑映射
<img src="https://www.zhihu.com/equation?tex=f" alt="f" eeimg="1">
将每个实数
<img src="https://www.zhihu.com/equation?tex=a" alt="a" eeimg="1">
映射到对应拓扑基中元素
<img src="https://www.zhihu.com/equation?tex=U_a" alt="U_a" eeimg="1">
。注意到这样的映射是单的(集合最小元不同)。故这说明拓扑基的大小至少与实数域一样大,不可数!
</p>
<p>
这个例子中证明C2不成立是通过
<b>
寻找拓扑基中开集特征+建立不可数集合到拓扑基的单射
</b>
完成的。不幸的是这样的方法常常难以构造,故之后我们会借助一些定理得到其它的证明非C2的方法。
</p>
<p>
<br>
</p>
<p>
<br>
</p>
<p>
<b>
关于两条可数性公理之间的关系:
</b>
</p>
<p>
<b>
C2可以推出C1
</b>
。这是显然的,取含
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的拓扑基中元素构成集合,则必定为一个
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的邻域基。(注意到拓扑基比邻域基要求更严格)
</p>
<p>
<b>
C2空间必定可分。
</b>
(可分指存在可数稠密子集)在每个拓扑基元素中各任取一点构成集合
<img src="https://www.zhihu.com/equation?tex=A" alt="A" eeimg="1">
,则由于C2,
<img src="https://www.zhihu.com/equation?tex=A" alt="A" eeimg="1">
可数。由于每个元素均在拓扑基中,故
<img src="https://www.zhihu.com/equation?tex=%5Cforall+x%5Cin+X" alt="\forall x\in X" eeimg="1">
,任意
<img src="https://www.zhihu.com/equation?tex=x" alt="x" eeimg="1">
的开邻域
<img src="https://www.zhihu.com/equation?tex=U" alt="U" eeimg="1">
,总是存在拓扑基中元素
<img src="https://www.zhihu.com/equation?tex=V" alt="V" eeimg="1">
,使得
<img src="https://www.zhihu.com/equation?tex=V%5Csubset+U" alt="V\subset U" eeimg="1">
。则
<img src="https://www.zhihu.com/equation?tex=%5Cexists+a%5Cin+A%2Ca%5Cin+V" alt="\exists a\in A,a\in V" eeimg="1">
,即
<img src="https://www.zhihu.com/equation?tex=a%5Cin%28U-%5Cleft+%5C%7B+x+%5Cright+%5C%7D%29%5Ccap+A" alt="a\in(U-\left \{ x \right \})\cap A" eeimg="1">
,
<img src="https://www.zhihu.com/equation?tex=%28U-%5Cleft+%5C%7B+x+%5Cright+%5C%7D%29%5Ccap+A%5Cneq+%5Cvarnothing" alt="(U-\left \{ x \right \})\cap A\neq \varnothing" eeimg="1">
。
</p>
<p>
故
<img src="https://www.zhihu.com/equation?tex=%5Coverline%7BA%7D%3DX" alt="\overline{A}=X" eeimg="1">
,
<img src="https://www.zhihu.com/equation?tex=A" alt="A" eeimg="1">
为可数稠密子集,拓扑空间可分。
</p>
<p>
<br>
</p>
<p>
另外,
<b>
C1与C2公理都具有遗传性与可乘性
</b>
,读者容易自证。
</p>
<p>
<br>
</p>
<p>
<br>
</p>
<p>
接下来我会说说Lindelof定理,公理之间更多的联系,以及度量拓扑所具有的良好性质。下一次我可能会补充更多例题。
</p>
</div>
</div>
</body>
</html>
|
# Projeto Calculadora
Este é um projeto de uma calculadora simples implementada em C#.
## Funcionalidades
A calculadora possui as seguintes funcionalidades:
- `Somar(int a, int b)`: Retorna a soma de dois números inteiros.
- `Subtrair(int a, int b)`: Retorna a subtração de dois números inteiros.
- `Multiplicar(int a, int b)`: Retorna o produto de dois números inteiros.
- `Dividir(int a, int b)`: Retorna a divisão de dois números inteiros.
## Testes
O projeto inclui testes unitários para garantir o correto funcionamento das operações matemáticas.
### Testes Incluídos
- `Somar`: Verifica se a função `Somar` retorna o resultado esperado.
- `Subtrair`: Verifica se a função `Subtrair` retorna o resultado esperado.
- `Multiplicar`: Verifica se a função `Multiplicar` retorna o resultado esperado.
- `Dividir`: Verifica se a função `Dividir` retorna o resultado esperado.
## Como Usar
Para utilizar a calculadora em seu próprio projeto, siga os passos abaixo:
1. Copie os arquivos `Calculadora.cs` para o seu projeto.
2. Importe o namespace `Calculadora` no arquivo onde deseja utilizar a calculadora.
3. Utilize as funções de acordo com suas necessidades.
### Exemplo de Uso
```csharp
using Calculadora;
class Program
{
static void Main()
{
int resultadoSoma = Calculadora.Somar(10, 10);
Console.WriteLine("A soma de 10 e 10 é: " + resultadoSoma);
}
}
|
import 'package:flutter/material.dart';
class SummaryItem extends StatelessWidget {
SummaryItem(this.title, this.value);
String title;
String value;
@override
Widget build(BuildContext context) {
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
margin: EdgeInsets.all(20),
elevation: 7,
child: Container(
height: 150,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.blue.shade400,
borderRadius: BorderRadius.circular(20),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(title,
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.black54)),
Text(value, style: TextStyle(fontSize: 50, color: Colors.white)),
],
)),
),
);
}
}
|
import {useState,useEffect} from "react";
function App() {
const [products,setProducts]=useState([]);
const [page,setPage]=useState(1);
const [totalPages,setTotalPages]=useState(0);
async function fetchData(){
const data=await fetch(`https://dummyjson.com/products?limit=10&skip=${page*10-10}`);
const jsonData=await data.json();
// console.log(jsonData.products);
// console.log(jsonData.total);
if(jsonData && jsonData.products){
setProducts(jsonData.products);
setTotalPages(jsonData.total / 10)
}
}
useEffect(()=>{
fetchData()
},[page]);
const pageHandler=(selectedPage)=>{
if(selectedPage>=1 && selectedPage<=totalPages && selectedPage!==page)
setPage(selectedPage);
}
return (
<div className="App">
{products.length>0 && (<div className="products">
{products.map((item)=>{
return <div key={item.id} className="product">
<img src={item.thumbnail} alt={item.title}/>
<p>{item.title}</p>
</div>
})}
</div>)}
{products.length>0 && (<div className="pagination">
<span className={page>1?"":"pagination_disabled"} onClick={()=>pageHandler(page-1)}>◀️</span>
{[...Array(totalPages)].map((_,i)=>{
return <span key={i} onClick={()=>pageHandler(i+1)} className={page===i+1?"pagination_selected":""}>
{i+1}
</span>
})}
<span className={page<totalPages?"":"pagination_disabled"} onClick={()=>pageHandler(page+1)}>▶️</span>
</div>)}
</div>
);
}
export default App;
|
package nand2tetris.translator.part.two;
import java.util.Arrays;
import java.util.Optional;
public enum MemorySegment {
LOCAL("local"),
ARGUMENT("argument"),
THIS("this"),
THAT("that"),
CONSTANT("constant"),
STATIC("static"),
POINTER("pointer"),
TEMP("temp");
private String memorySegment;
MemorySegment(String operation) {
this.memorySegment = operation;
}
public String getOperation() {
return memorySegment;
}
public static Optional<MemorySegment> get(String url) {
return Arrays.stream(MemorySegment.values())
.filter(env -> env.memorySegment.equals(url))
.findFirst();
}
}
|
from typing import Callable
import numpy as np
from scipy.optimize import curve_fit, minimize
from scipy.optimize import minimize_scalar
from scipy.ndimage import binary_dilation
from scipy.interpolate import interp1d
from sklearn.preprocessing import PolynomialFeatures
import numdifftools as nd
from pfs.ga.pfsspec.core.util.copy import safe_deep_copy
from pfs.ga.pfsspec.core.util.args import get_arg
from pfs.ga.pfsspec.core import Physics
from pfs.ga.pfsspec.core.sampling import MCMC
from pfs.ga.pfsspec.core.caching import ReadOnlyCache
from pfs.ga.pfsspec.core.obsmod.resampling import RESAMPLERS
from pfs.ga.pfsspec.core.sampling import Parameter, Distribution
from .tempfittrace import TempFitTrace
from .tempfittracestate import TempFitTraceState
from .tempfitresults import TempFitResults
from .fluxcorr import FluxCorr
from .setup_logger import logger
class TempFit():
"""
This is the base class for basic RV estimation based on template fitting using a non-linear
maximum likelihood or maximum significance method. Templates are optionally convolved with
the instrumental LSF. The class supports various methods to determine the uncertainty of
RV estimates.
The input should be presented as a dictionary of lists of spectra with the dictionary keys
being the various spectrograph arms whereas the spectra within the lists are the single
exposures.
When the objective is fitting the template parameters, use ModelGridTempFit instead.
Derived classes, with the use of the appropriate mix-ins are capable of fitting templates
with a multiplicative flux correction function or a continuum model. In either case, a
multiplicative scalar amplitude is fitted, either
Some terminology: amplitudes are scalar factors to be applied to observed spectra to scale to
the templates. Coefficients are the flux correction or continuum fit model parameters.
"""
def __init__(self, trace=None, correction_model=None, orig=None):
"""
Initialize the template fitting problem.
"""
if not isinstance(orig, TempFit):
self.trace = trace # Collect debug info
self.correction_model = correction_model # Flux correction or continuum fitting model
self.template_psf = None # Dict of psf to downgrade templates with
self.template_resampler = RESAMPLERS['fluxcons']() # Resample template to instrument pixels
self.template_cache_resolution = 50 # Cache templates with this resolution in RV
self.template_wlim = None # Model wavelength limits for each spectrograph arm
self.template_wlim_buffer = 100 # Wavelength buffer in A, depends on line spread function
self.cache_templates = False # Cache PSF-convolved templates
self.rv_0 = None # RV initial guess
self.rv_fixed = False # Fix RV to the initial guess or default value
self.rv_bounds = None # Find RV between these bounds
self.rv_prior = None
self.rv_step = None # RV step size for MCMC sampling
# Variables controlling flux correction
self.amplitude_per_arm = False # Estimate flux multiplier for each arm independently
self.amplitude_per_fiber = False
self.amplitude_per_exp = False
# Other variables
self.spec_norm = None # Spectrum (observation) normalization factor
self.temp_norm = None # Template normalization factor
self.use_mask = True # Use mask from spectrum, if available
self.mask_bits = None # Mask bits (None means any)
self.use_error = True # Use flux error from spectrum, if available
self.use_weight = False # Use weight from template, if available
self.max_iter = 1000 # Maximum number of iterations of the optimization algorithm
self.mcmc_step = 10.0 # MCMC initial step size
self.mcmc_walkers = 10 # Number of parallel walkers
self.mcmc_burnin = 100 # Number of burn-in iterations
self.mcmc_samples = 100 # Number of samples
self.mcmc_gamma = 0.99 # Adaptive MCMC proposal memory
self.mcmc_thin = 1 # MCMC trace thinning
else:
self.trace = trace if trace is not None else orig.trace
self.correction_model = correction_model if correction_model is not None else orig.correction_model
self.template_psf = orig.template_psf
self.template_resampler = orig.template_resampler
self.template_cache_resolution = orig.template_cache_resolution
self.template_wlim = orig.template_wlims
self.template_wlim_buffer = orig.template_wlim_buffer
self.cache_templates = orig.cache_templates
self.rv_0 = orig.rv_0
self.rv_bounds = orig.rv_bounds
self.rv_prior = orig.rv_prior
self.rv_step = orig.rv_step
self.amplitude_per_arm = orig.amplitude_per_arm
self.amplitude_per_fiber = orig.amplitude_per_fiber
self.amplitude_per_exp = orig.amplitude_per_exp
self.spec_norm = orig.spec_norm
self.temp_norm = orig.temp_norm
self.use_mask = orig.use_mask
self.mask_bits = orig.mask_bits
self.use_error = orig.use_error
self.use_weight = orig.use_weight
self.max_iter = orig.max_iter
self.mcmc_step = orig.mcmc_step
self.mcmc_walkers = orig.mcmc_walkers
self.mcmc_burnin = orig.mcmc_burnin
self.mcmc_samples = orig.mcmc_samples
self.mcmc_thin = orig.mcmc_thin
self.mcmc_thin = orig.mcmc_gamma
self.reset()
def reset(self):
self.template_cache = ReadOnlyCache()
if self.correction_model is not None:
self.correction_model.reset()
def add_args(self, config, parser):
Parameter('rv').add_args(parser)
parser.add_argument('--amplitude-per-arm', action='store_true', dest='amplitude_per_arm', help='Flux correction per arm.\n')
parser.add_argument('--amplitude-per-fiber', action='store_true', dest='amplitude_per_fiber', help='Flux correction per fiber.\n')
parser.add_argument('--amplitude-per-exp', action='store_true', dest='amplitude_per_exp', help='Flux correction per exposure.\n')
parser.add_argument('--resampler', type=str, choices=list(RESAMPLERS.keys()), default='fluxcons', help='Template resampler.\n')
parser.add_argument('--mask', action='store_true', dest='use_mask', help='Use mask from spectra.\n')
parser.add_argument('--no-mask', action='store_false', dest='use_mask', help='Do not use mask from spectra.\n')
parser.add_argument('--mask-bits', type=int, help='Bit mask.\n')
parser.add_argument('--mcmc-walkers', type=int, help='Number of MCMC walkers (min number of params + 1).\n')
parser.add_argument('--mcmc-burnin', type=int, help='Number of MCMC burn-in samples.\n')
parser.add_argument('--mcmc-samples', type=int, help='Number of MCMC samples.\n')
parser.add_argument('--mcmc-thin', type=int, help='MCMC chain thinning interval.\n')
parser.add_argument('--mcmc-gamma', type=float, help='Adaptive MC gamma.\n')
if self.correction_model is not None:
self.correction_model.add_args(config, parser)
def init_from_args(self, script, config, args):
if self.trace is not None:
self.trace.init_from_args(script, config, args)
rv = Parameter('rv')
rv.init_from_args(args)
step = rv.generate_step_size(step_size_factor=0.1)
self.rv_0 = rv.value # RV initial guess
self.rv_bounds = [rv.min, rv.max] # Find RV between these bounds
self.rv_prior = rv.get_dist()
self.rv_step = step # RV step size for MCMC sampling
self.amplitude_per_arm = get_arg('amplitude_per_arm', self.amplitude_per_arm, args)
self.amplitude_per_fiber = get_arg('amplitude_per_fiber', self.amplitude_per_fiber, args)
self.amplitude_per_exp = get_arg('amplitude_per_exp', self.amplitude_per_exp, args)
# Use Interp1dResampler when template PSF accounts for pixelization
resampler = get_arg('resampler', None, args)
if resampler is None:
pass
elif resampler in RESAMPLERS:
self.template_resampler = RESAMPLERS[resampler]()
else:
raise NotImplementedError()
self.use_mask = get_arg('use_mask', self.use_mask, args)
self.mask_bits = get_arg('mask_bits', self.mask_bits, args)
self.use_error = get_arg('use_error', self.use_error, args)
self.use_weight = get_arg('use_weight', self.use_weight, args)
self.mcmc_walkers = get_arg('mcmc_walkers', self.mcmc_walkers, args)
self.mcmc_burnin = get_arg('mcmc_burnin', self.mcmc_burnin, args)
self.mcmc_samples = get_arg('mcmc_samples', self.mcmc_samples, args)
self.mcmc_thin = get_arg('mcmc_thin', self.mcmc_thin, args)
# Initialize the continuum correction model
if self.correction_model is not None:
self.correction_model.init_from_args(script, config, args)
def create_trace(self):
return TempFitTrace()
def determine_wlim(self, spectra: dict, /, per_arm=True, per_exp=True,
rv_bounds=None, wlim_buffer=None, round_to=None):
"""
Determine the wave limits for each arm separately or all arms together, for each
exposure or all exposures together.
Parameters
----------
spectra : dict or dict of lists
Dictionary of spectra, keyed by arm name, optionally with multiple exposures in a list.
per_arm : bool
Whether to determine the wave limits separately for each arm
per_exp : bool
Whether to determine the wave limits separately for each exposure
rv_bounds : tuple
RV bounds to extend the wavelength limits with
wlim_buffer : float
Buffer to add to the wavelength limits
Returns
-------
dict or list or tuple
Dictionary of wavelength limits for each arm, or list of wavelength limits for each exposure,
or a tuple of wavelength limits for all arms and exposures.
"""
rv_bounds = rv_bounds if rv_bounds is not None else self.rv_bounds
wlim_buffer = wlim_buffer if wlim_buffer is not None else self.template_wlim_buffer
if rv_bounds is not None:
zmin = Physics.vel_to_z(rv_bounds[0])
zmax = Physics.vel_to_z(rv_bounds[1])
else:
zmin = zmax = None
def buffer_limits(wmin, wmax):
# Given the wavelength coverage and rv_bounds, calculate the appropriate
# domain for the flux correction basis or continuum model
if zmin is not None:
wmin = wmin * (1 + zmin)
if zmax is not None:
wmax = wmax * (1 + zmax)
if wlim_buffer is not None:
wmin -= wlim_buffer
wmax += wlim_buffer
if round_to is not None:
wmin = np.floor(wmin / round_to) * round_to
wmax = np.ceil(wmax / round_to) * round_to
return (wmin, wmax)
if per_arm:
# Use a different flux correction (at least in terms of domain) for each arm
wlim = {}
for arm in spectra:
if per_exp:
# Separately for each arm and each exposure
wlim[arm] = []
for ei, spec in enumerate(spectra[arm] if isinstance(spectra[arm], list) else [spectra[arm]]):
if spec is not None:
[wmin, wmax] = spec.wave[~np.isnan(spec.wave)][[0, -1]]
wlim[arm].append(buffer_limits(wmin, wmax))
else:
wlim[arm].append(None)
else:
# Separately for each arm but for all exposures
found = False
wmin, wmax = None, None
for ei, spec in enumerate(spectra[arm] if isinstance(spectra[arm], list) else [spectra[arm]]):
if spec is not None:
w = spec.wave[~np.isnan(spec.wave)][[0, -1]]
wmin = min(wmin or w[0], w[0])
wmax = max(wmax or w[1], w[1])
found = True
if found:
wlim[arm] = buffer_limits(wmin, wmax)
else:
raise Exception("No valid spectra found to determine the wavelength limits.")
else:
# Use the same flux correction for each arm, the domain will cover all arms
if per_exp:
# A single model for each arm, separately for each exposure
# Assume that the exposures match up in the arms
wmin, wmax = None, None
found = False
exp_count = {}
for arm in spectra:
for ei, spec in enumerate(spectra[arm] if isinstance(spectra[arm], list) else [spectra[arm]]):
if spec is not None:
w = spec.wave[~np.isnan(spec.wave)][[0, -1]]
wmin = min(wmin or w[0], w[0])
wmax = max(wmax or w[1], w[1])
found = True
# Check if the exposures match up in all arms
exp_count = np.unique([ len(spectra[arm]) if isinstance(spectra[arm], list) else 1 for arm in spectra ])
if exp_count.size > 1:
raise Exception("Exposures do not match up in the arms.")
if found:
wlim = []
for i in range(exp_count[0]):
wlim.append(buffer_limits(wmin, wmax))
else:
raise Exception("No valid spectra found to determine the wavelength limits.")
else:
# A single model for all arms and exposures
wmin, wmax = None, None
found = False
for arm in spectra:
for ei, spec in enumerate(spectra[arm] if isinstance(spectra[arm], list) else [spectra[arm]]):
if spec is not None:
w = spec.wave[~np.isnan(spec.wave)][[0, -1]]
wmin = min(wmin or w[0], w[0])
wmax = max(wmax or w[1], w[1])
found = True
if found:
wlim = buffer_limits(wmin, wmax)
else:
raise Exception("No valid spectra found to initialize the flux correction model.")
return wlim
def init_models(self, spectra, rv_bounds=None, force=False):
"""
Initialize the models for flux correction or continuum fitting
"""
if self.correction_model is not None:
self.correction_model.trace = self.trace
self.correction_model.tempfit = self
self.correction_model.init_models(spectra, rv_bounds=rv_bounds, force=force)
def init_model(self, spectra, /, per_arm=True, per_exp=True,
rv_bounds=None, wlim_buffer=None, round_to=None,
create_model_func=None):
"""
Create model instances for flux correction or continuum fitting for each arm
and exposure, depending on the settings.
The returned data structure is either a dict or lists, or model type or the
combination of these.
Parameters
----------
spectra : dict or dict of lists
Dictionary of spectra, keyed by arm name
per_arm : bool
Whether to initialize a model for each arm
per_exp : bool
Whether to initialize a model for each exposure
rv_bounds : tuple
RV bounds to extend the wavelength limits with
wlim_buffer : float
Buffer to add to the wavelength limits
round_to : float
Round the wavelength limits to this quantum
create_model_func : callable
Function to create the model instance
Returns
-------
dict or list or tuple
Dictionary of models for each arm, or list of models for each exposure,
or a tuple of models for all arms and exposures.
"""
def init_model_helper(wlim):
if isinstance(wlim, dict):
model = { arm: init_model_helper(wlim[arm]) for arm in wlim }
elif isinstance(wlim, list):
model = [ init_model_helper(wlim) for wlim in wlim ]
elif isinstance(wlim, tuple):
model = create_model_func(wlim)
return model
wlim = self.determine_wlim(spectra, per_arm=per_arm, per_exp=per_exp,
rv_bounds=rv_bounds, wlim_buffer=wlim_buffer, round_to=round_to)
model = init_model_helper(wlim)
return model
def get_model(self, model, arm, ei, per_arm=True, per_exp=True):
"""
Get the model for the given arm and exposure index
"""
if isinstance(model, dict):
return model[arm][ei]
elif isinstance(model, list):
return model[ei]
else:
return model
def get_normalization(self, spectra, templates, rv_0=None):
"""
Calculate a normalization factor for the spectra, as well as
the templates assuming an RV=0 from the median flux.
Parameters
----------
spectra : dict of Spectrum or dict of list of Spectrum
Observed spectra
templates : dict of Spectrum
Synthetic stellar templates for each arm
rv_0 : float
Radial velocity
Returns
-------
float, float
Normalization factors for spectra and templates
This is just a factor to bring spectra to the same scale and avoid
very large numbers in the Fisher matrix or elsewhere.
"""
rv_0 = rv_0 if rv_0 is not None else self.rv_0
s = []
t = []
for arm in spectra:
for ei, spec in enumerate(spectra[arm] if isinstance(spectra[arm], list) else [spectra[arm]]):
if spec is not None:
mask = spec.mask_as_bool()
spec = self.process_spectrum(arm, ei, spec)
s.append(spec.flux[mask & ~np.isnan(spec.flux) & (spec.flux > 0)])
if self.template_psf is not None:
psf = self.template_psf[arm]
else:
psf = None
if self.template_wlim is not None:
wlim = self.template_wlim[arm]
else:
wlim = None
if rv_0 is not None:
rv = rv_0
else:
rv = 0.0
if spec is not None:
temp = self.process_template(arm, templates[arm], spec, rv, psf=psf, wlim=wlim)
t.append(temp.flux)
if len(s) == 0 or len(t) == 0:
raise ValueError('No valid flux values found in spectra or templates')
spec_flux = np.concatenate(s)
temp_flux = np.concatenate(t)
return np.median(spec_flux), np.median(temp_flux)
def process_spectrum(self, arm, i, spectrum):
"""
Preprocess the spectrum for the purposes of evaluating likelihood function.
Parameters
----------
arm : str
Spectrograph arm
i : int
Exposure index
spectrum : Spectrum
Observed spectrum
Returns
-------
Spectrum
Preprocessed spectrum
This step currently consist only of normalizing the flux with a factor.
"""
# Do not modifiy the original observed spectrum
spec = spectrum.copy()
# Normalize flux and flux_err
if self.spec_norm is not None:
spec.multiply(1.0 / self.spec_norm)
# Determine the binary mask used for template fitting
spec.mask = self.get_full_mask(spec)
# Take flux error and calculate its squared
if self.use_error and spec.flux_err is not None:
spec.sigma2 = spec.flux_err ** 2
spec.mask &= ~np.isnan(spec.sigma2)
else:
spec.sigma2 = None
if self.trace is not None:
self.trace.on_process_spectrum(arm, i, spectrum, spec)
return spec
def preprocess_spectra(self, spectra):
# Preprocess the observed spectra, mask, weight etc.
# These are independent of RV
pp_spec = { arm: [] for arm in spectra }
for arm in spectra:
for ei, s in enumerate(spectra[arm] if isinstance(spectra[arm], list) else [ spectra[arm] ]):
if s is not None:
spec = self.process_spectrum(arm, ei, s)
pp_spec[arm].append(spec)
else:
pp_spec[arm].append(None)
return pp_spec
def process_template_impl(self, arm, template, spectrum, rv, psf=None, wlim=None):
"""
Preprocesses a template for the purposes of evaluting the likelihood function.
Parameters
----------
arm : str
Spectrograph arm
template : dict of Spectrum
Synthetic stellar template, for each arm
spectrum : dict of Spectrum or dict of list of Spectrum
Observed spectrum
rv : float
Radial velocity
psf : dict of Psf
Instrumental line spread function, for each arm
wlim : tuple
Wavelength limits for the convolution
Returns
-------
Spectrum
Preprocessed template
This step is essentially a simulating an observation without calculating any
uncertainties which consits of a convolution and a normalization step.
"""
# 1. Make a copy, not in-place update
t = template.copy()
# 2. Shift template to the desired RV
t.set_rv(rv)
# 3. If a PSF if provided, convolve down template to the instruments
# resolution. Otherwise assume the template is already convolved.
# Not that psf is often None when the convolution is pushed down to
# the ModelGrid object for better cache performance.
if psf is not None:
t.convolve_psf(psf, wlim=wlim)
# 4. Normalize by a factor
if self.temp_norm is not None:
t.multiply(1.0 / self.temp_norm)
# TODO: calculate weight vector from the template
return t
def process_template(self, arm, template, spectrum, rv, psf=None, wlim=None, diff=False, resample=True):
"""
Preprocess the template to match the observation.
Parameters
----------
arm : str
Spectrograph arm
template : Spectrum
Synthetic stellar template
spectrum : dict of Spectrum or dict of list of Spectrum
Observed spectrum
rv : float
Radial velocity
psf : Psf
Instrumental line spread function
wlim : tuple
Wavelength limits for the convolution
diff : bool
Calculate the derivative of the template
resample : bool
Resample the template to the observation pixels
Returns
-------
Spectrum
Preprocessed template
This step involves shifting the high resolution template the a given RV,
convolving it with the PSF, still at high resolution, and normalizing
by a factor.
To improve performance, pre-processed templates are cached at quantized
values of RV and reused when the requested RV is close to one in the
cache. This is fine as long as the PFS changes slowly with wavelength
which is most often the case. Still, templates sometimes get shifted
significantly when the target's RV is large so a single precomputed
template is not enough.
The template is always kept at high resolution during transformations
until it's resampled to the spectrum pixels using a flux-conserving
resampler.
"""
psf = psf if psf is not None else (self.template_psf[arm] if self.template_psf is not None else None)
wlim = wlim if wlim is not None else (self.template_wlim[arm] if self.template_wlim is not None else None)
temp = None
# If `cache_templates` is True, we can look up a template that's already been
# convolved down with the PSF. Otherwise we just shift the template and do the
# convolution on the fly.
if self.cache_templates:
# Quantize RV to the requested cache resolution
rv_q = np.floor(rv / self.template_cache_resolution) * self.template_cache_resolution
key = (template, rv_q)
# Look up template in cache and shift to from quantized RV to actual RV
if self.template_cache.is_cached(key):
temp = self.template_cache.get(key)
if self.trace is not None:
self.trace.on_template_cache_hit(template, rv_q, rv)
else:
temp = self.process_template_impl(arm, template, spectrum, rv_q, psf=psf, wlim=wlim)
if self.trace is not None:
self.trace.on_template_cache_miss(template, rv_q, rv)
self.template_cache.push(key, temp)
# Shift from quantized RV to requested RV
temp = temp.copy()
temp.set_restframe()
temp.apply_redshift(Physics.vel_to_z(rv))
else:
# Compute convolved template from scratch
temp = self.process_template_impl(arm, template, spectrum, rv, psf=psf, wlim=wlim)
if self.trace is not None:
self.trace.on_process_template(arm, rv, template, temp)
# Resample template to the binning of the observation
if resample:
temp.apply_resampler(self.template_resampler, spectrum.wave, spectrum.wave_edges)
if self.trace is not None:
self.trace.on_resample_template(arm, rv, spectrum, template, temp)
# Create a mask based on the wavelength coverate
temp.mask = self.get_full_mask(temp)
return temp
def preprocess_templates(self, spectra, templates, rv):
# Pre-process each exposure in each arm and pass them to the log L calculator
# function of the flux correction or continuum fit model.
pp_temp = { arm: [] for arm in spectra }
for arm in spectra:
for ei, spec in enumerate(spectra[arm] if isinstance(spectra[arm], list) else [ spectra[arm] ]):
if spec is not None:
temp = self.process_template(arm, templates[arm], spec, rv)
pp_temp[arm].append(temp)
else:
pp_temp[arm].append(None)
return pp_temp
def diff_template(self, template, wave=None):
"""
Calculate the numerical derivative of the template and optionally resample
to a new wavelength grid using linear interpolation
"""
dfdl = np.empty_like(template.wave)
dfdl[1:-1] = (template.flux[2:] - template.flux[:-2]) / (template.wave[2:] - template.wave[:-2])
dfdl[0] = dfdl[1]
dfdl[-1] = dfdl[-2]
if wave is not None:
ip = interp1d(template.wave, dfdl, bounds_error=False, fill_value=np.nan)
dfdl = ip(wave)
else:
wave = template.wave
return wave, dfdl
def log_diff_template(self, template, wave=None):
"""
Calculate the numerical log-derivative of the template and optionally resample
to a new wavelength grid using linear interpolation
"""
dfdlogl = np.empty_like(template.wave)
dfdlogl[1:-1] = template.wave[1:-1] * (template.flux[2:] - template.flux[:-2]) / (template.wave[2:] - template.wave[:-2])
dfdlogl[0] = dfdlogl[1]
dfdlogl[-1] = dfdlogl[-2]
if wave is not None:
ip = interp1d(template.wave, dfdlogl, bounds_error=False, fill_value=np.nan)
dfdlogl = ip(wave)
else:
wave = template.wave
return wave, dfdlogl
def get_amp_count(self, spectra: dict):
"""
Calculate the number of different amplitudes to be fitted.
Parameters
----------
spectra : dict of Spectrum or dict of list of Spectrum
Observed spectra
Returns
-------
int
Number of amplitudes to be fitted
Depending on the mode of fitting, different amplitudes are fitted on a per arm
and/or per exposure basis to correct for fluxing artefacts.
Amplitudes are independent of flux correction models (which are linear combinations
of function excluding the constant function) and continuum models (which don't account
for a multiplier) but handled differently for flux correction models and continuum models.
"""
if self.amplitude_per_exp:
amp_count = 0
for arm in spectra:
for s in spectra[arm] if isinstance(spectra[arm], list) else [ spectra[arm] ]:
if s is not None:
amp_count += 1
elif self.amplitude_per_arm:
amp_count = 0
for arm in spectra:
found = False
for s in spectra[arm] if isinstance(spectra[arm], list) else [ spectra[arm] ]:
if s is not None:
found = True
break
if found:
amp_count += 1
else:
amp_count = 1
if amp_count == 0:
raise ValueError('No valid spectra found')
if self.amplitude_per_fiber:
raise NotImplementedError()
return amp_count
def get_full_mask(self, spec, mask_bits=None):
"""
Return the full mask for the spectrum, including the mask from the spectrum
and the mask nan and inf values.
Parameters
----------
spec : Spectrum
Spectrum
mask_bits : int
Flag bits to consider as masked pixels.
Returns
-------
ndarray
Boolean mask in the shape of the wave array
"""
mask_bits = mask_bits if mask_bits is not None else self.mask_bits
mask = None
if self.use_mask and spec.mask is not None:
# TODO: mask bits can be different for each spectrum
mask = spec.mask_as_bool(bits=mask_bits)
if mask is None:
mask = np.full_like(spec.wave, True, dtype=bool)
# Mask out nan values which might occur if spectrum mask is not properly defined
mask &= ~(np.isnan(spec.wave) | np.isinf(spec.wave))
mask &= ~(np.isnan(spec.flux) | np.isinf(spec.flux))
if spec.flux_err is not None:
mask &= ~(np.isnan(spec.flux_err) | np.isinf(spec.flux_err))
# Flux error
if self.use_error and spec.flux_err is not None:
mask &= (spec.flux_err / spec.flux) > 1e-5
return mask
def eval_prior(self, prior, x):
"""
Evaluates a prior in the form of a distribution of callable function.
Parameters
----------
prior : Distribution or callable
Prior distribution or function that returns a normalized probability.
x : float
Value to evaluate the prior at
Returns
-------
float
Log of the prior probability density at x
"""
if prior is None:
return 0
elif isinstance(prior, Distribution):
return prior.log_pdf(x)
elif isinstance(prior, Callable):
return prior(x)
else:
raise NotImplementedError()
# TODO: this uses emcee but isn't very good and has been replaced by a simple
# adaptive MCMC that works better; consider deleting
# def sample_log_L(self, log_L_fun, x_0,
# walkers=None, burnin=None, samples=None, thin=None, cov=None):
# walkers = walkers if walkers is not None else self.mcmc_walkers
# burnin = burnin if burnin is not None else self.mcmc_burnin
# samples = samples if samples is not None else self.mcmc_samples
# thin = thin if thin is not None else self.mcmc_thin
# ndim = x_0.size
# # TODO: it's good to run many walkers but it increases time spent
# # in burn-in a lot
# # nwalkers = max(walkers, 2 * x_0.size + 1)
# nwalkers = walkers
# # TODO: delete, moved to init_mcmc
# # # Generate an initial state a little bit off of x_0
# # if step is None:
# # p_0 = x_0 * (1 + 0.05 * np.random.uniform(-1.0, 1.0, size=(nwalkers, ndim)))
# # else:
# # p_0 = x_0 + np.random.uniform(-1.0, 1.0, size=(nwalkers, ndim)) * step
# p_0 = np.broadcast_to(x_0, (nwalkers, ndim))
# # # Make sure the initial state is inside the bounds
# # if bounds is not None:
# # p_0 = np.where(bounds[..., 0] < p_0, p_0, bounds[..., 0])
# # p_0 = np.where(bounds[..., 1] > p_0, p_0, bounds[..., 1])
# if cov is not None:
# # moves = [ emcee.moves.GaussianMove(cov), emcee.moves.StretchMove(live_dangerously=True) ]
# moves = [
# # emcee.moves.GaussianMove(cov),
# # emcee.moves.GaussianMove(10 * cov),
# # emcee.moves.GaussianMove(0.1 * cov)
# emcee.moves.GaussianMove(np.diag(cov), mode="sequential"),
# ]
# else:
# # moves = [ emcee.moves.StretchMove(live_dangerously=True), emcee.moves.WalkMove(live_dangerously=True) ]
# moves = [ emcee.moves.StretchMove(live_dangerously=True) ]
# sampler = emcee.EnsembleSampler(nwalkers, ndim, log_L_fun, moves=moves)
# # Run the burn-in with the original proposal
# # Allocate array for the adaptive run
# state = sampler.run_mcmc(p_0, burnin, skip_initial_state_check=True)
# batch = 100
# nbatch = samples // batch
# ndim = sampler.chain.shape[-1]
# sampler.reset()
# # Periodically update the proposal distribution
# for b in range(nbatch):
# state = sampler.run_mcmc(state, batch, skip_initial_state_check=True)
# # if np.mean(sampler.acceptance_fraction) < 1e-2:
# # C = moves[0].get_proposal.scale * 0.8
# # else:
# # x = sampler.chain.reshape(-1, ndim)
# # m = np.mean(x, axis=0)
# # C = np.matmul((x - m).T, x - m) / x.shape[0]
# # # # TODO: add some logic to test if C is a valid proposal
# # moves[0].get_proposal.scale = (2.38**2 / ndim) * C
# if thin is not None:
# s = np.s_[..., ::thin, :]
# else:
# s = ()
# # shape: (chains, samples, params)
# return sampler.chain[s], sampler.lnprobability[s]
#region Fisher matrix evaluation
# There are multiple ways of evaluating the Fisher matrix. Functions
# with _full_ return the full Fisher matrix including matrix elements for
# the flux correction coefficients and rv. Functions with _rv_ return
# the (single) matrix element corresponding to the RV only. Functions with
# _hessian depend on the numerical evaluation of the Hessian with respect
# to the parameters of the fitted model.
def get_param_packing_functions(self, mode='full'):
"""
Return parameter packing functions that combine the correction model parameters
with the rest of the parameters. These functions are used by the optimizer to
compose the array of parameters to optimize over.
Parameters
----------
mode : str
Optimization mode, either 'full', 'a', 'rv', or 'a_rv', where 'full' means
pack all parameters, 'a' means pack only the correction model parameters,
'rv' means pack only the RV, and 'a_rv' means pack both the correction model
parameters and the RV.
Returns
-------
tuple
Tuple of functions that pack and unpack the parameters, and a function that
packs the parameter bounds.
This function returns 2d arrays, where the first index runs over the multiple
sets of parameters.
"""
# Correction model packing functions
pp_a, up_a, pb_a = self._get_param_packing_functions_a(mode=mode)
# Other parameter packing functions
pp_rv, up_rv, pb_rv = self._get_param_packing_functions_rv(mode=mode)
if mode == 'full' or (pp_a is not None and pp_rv is not None):
# Combine correction model coefficients with RV
def pack_params(a, rv):
rv = pp_rv(rv)
a = pp_a(a)
if a.ndim < 2 and rv.size > 1:
a = a[None, :]
return np.concatenate([ a, rv ], axis=-1)
def unpack_params(a_rv):
rv = up_rv(a_rv[..., -1])
if np.ndim(rv) > 1:
rv = rv.squeeze(0)
if isinstance(rv, np.ndarray) and np.size(rv) == 1:
rv = rv.item()
a = up_a(a_rv[..., :-1])
return a, rv
def pack_bounds(a_bounds, rv_bounds):
return pb_a(a_bounds) + pb_rv(rv_bounds)
elif pp_a is not None:
pack_params, unpack_params, pack_bounds = pp_a, up_a, pb_a
elif pp_rv:
pack_params, unpack_params, pack_bounds = pp_rv, up_rv, pb_rv
else:
raise NotImplementedError()
return pack_params, unpack_params, pack_bounds
def _get_param_packing_functions_a(self, mode='full'):
modes = mode.split('_')
if mode == 'full' or 'a' in modes:
def pack_params(a):
a = np.atleast_1d(a)
if np.ndim(a) < 2:
a = a[None, :]
return a
def unpack_params(a):
if a.ndim == 2 and a.shape[0] == 1:
a = np.squeeze(a, 0)
if a.size == 1:
a = a.item()
return a
def pack_bounds(a_bounds):
if a_bounds is None:
raise NotImplementedError()
else:
bounds = a_bounds
return bounds
else:
pack_params, unpack_params, pack_bounds = None, None, None
return pack_params, unpack_params, pack_bounds
def _get_param_packing_functions_rv(self, mode='full'):
modes = mode.split('_')
if mode == 'full' or 'rv' in modes:
def pack_params(rv):
rv = np.atleast_1d(rv)
if np.ndim(rv) < 2:
rv = rv[:, None]
return rv
def unpack_params(rv):
if np.ndim(rv) > 1 and rv.shape[0] == 1:
rv = rv.squeeze(0)
if isinstance(rv, np.ndarray) and np.size(rv) == 1:
rv = rv.item()
return rv
def pack_bounds(rv_bounds):
return [ rv_bounds ]
elif 'rv' not in modes:
# Only pack amplitude and flux correction or continuum parameters
pack_params, unpack_params, pack_bounds = None, None, None
else:
raise NotImplementedError()
return pack_params, unpack_params, pack_bounds
def get_objective_function(self, spectra, templates, rv_prior, mode='full'):
"""
Return the objective function and parameter packing/unpacking functions for optimizers
Parameters
----------
spectra : dict or dict of list
Dictionary of spectra for each arm and exposure
templates : dict
Dictionary of templates for each arm
rv_prior : Distribution or callable
RV prior function
mode : str
Determines how the model parameters are packed.
Returns
-------
log_L : callable
Log likelihood function
pack_params : callable
Function to pack individual parameters into a 1d array
unpack_params : callable
Function to unpack individual parameters from a 1d array
pack_bounds : callable
Function to pack parameter bounds into a list of tuples
"""
pack_params, unpack_params, pack_bounds = self.get_param_packing_functions(mode=mode)
if mode == 'full' or mode == 'a_rv':
def log_L(a_rv):
a, rv = unpack_params(a_rv)
log_L = self.calculate_log_L(spectra, templates, rv, rv_prior=rv_prior, a=a)
return log_L
elif mode == 'rv':
def log_L(rv):
rv = unpack_params(rv)
log_L = self.calculate_log_L(spectra, templates, rv, rv_prior=rv_prior)
return log_L
elif mode == 'a':
raise NotImplementedError()
else:
raise NotImplementedError()
return log_L, pack_params, unpack_params, pack_bounds
def get_bounds_array(self, bounds):
"""
Convert a list of bounds to a 2d array.
Parameters
----------
bounds : list of tuple
List of bounds for each parameter
Returns
-------
ndarray
2d array of bounds
If an element of `bounds` is None, or and element of the tuples is None,
the array will contain -inf and/or inf.
"""
if bounds is not None:
bb = []
for b in bounds:
if b is None:
bb.append((-np.inf, np.inf))
else:
bb.append((
b[0] if b[0] is not None else -np.inf,
b[1] if b[1] is not None else np.inf,
))
return np.array(bb)
else:
return None
def calculate_F(self, spectra, templates,
rv_0=None, rv_fixed=None, rv_bounds=None, rv_prior=None,
step=None, mode='full', method='hessian'):
"""
Evaluate the Fisher matrix around the provided rv_0.
Parameters
----------
spectra : dict of Spectrum or dict of list of Spectrum
Observed spectra
templates : dict of Spectrum
Synthetic stellar templates for each arm
rv_0 : float
Radial velocity around which the Hessian is evaluated
rv_fixed: bool
Whether to fix the RV during the optimization
rv_bounds : tuple
RV bounds to limit the numerical differentiation
rv_prior : Distribution or callable
Prior distribution for the RV
The corresponding a_0 best fit flux correction or continuum model
will be evaluated at the optimum. The Hessian is calculated wrt either
RV only, or rv and the flux correction coefficients.
Alternatively, the covariance matrix will be determined using MCMC.
"""
rv_0 = rv_0 if rv_0 is not None else self.rv_0
rv_fixed = rv_fixed if rv_fixed is not None else self.rv_fixed
rv_bounds = rv_bounds if rv_bounds is not None else self.rv_bounds
rv_prior = rv_prior if rv_prior is not None else self.rv_prior
# Get objective function
log_L, pack_params, unpack_params, pack_bounds = self.get_objective_function(
spectra, templates, rv_prior, mode=mode)
if mode == 'full' or mode == 'a_rv':
# Determine the flux correction or continuum fit parameters at the
# optimum RV
a_0 = self.calculate_coeffs(spectra, templates, rv_0)
x_0 = pack_params(a_0, rv_0)[0]
bounds = pack_bounds(np.size(a_0) * [(-np.inf, np.inf)], rv_bounds)
elif mode == 'rv':
x_0 = pack_params(rv_0)[0]
bounds = pack_bounds(rv_bounds)
else:
raise NotImplementedError()
bounds = self.get_bounds_array(bounds)
F, C = self.eval_F_dispatch(x_0, log_L, step, method, bounds)
if F.ndim > 2:
F = F.squeeze(0)
C = C.squeeze(0)
return F, C
def eval_F_dispatch(self, x_0, log_L_fun, step, method, bounds):
if method == 'hessian':
return self.eval_F_hessian(x_0, log_L_fun, step)
elif method == 'emcee':
return self.eval_F_emcee(x_0, log_L_fun, step, bounds)
elif method == 'sampling':
return self.eval_F_sampling(x_0, log_L_fun, step, bounds)
else:
raise NotImplementedError()
def eval_F_hessian(self, x_0, log_L_fun, step, inverse=True):
"""
Evaluate the Fisher matrix by calculating the Hessian numerically
"""
# Default step size is 1% of optimum values
if step is None:
step = 0.01 * x_0
dd_log_L = nd.Hessian(log_L_fun, step=step)
dd_log_L_0 = dd_log_L(x_0)
if inverse:
inv = np.linalg.inv(-dd_log_L_0)
else:
inv = None
return dd_log_L_0, inv
def eval_F_emcee(self, x_0, log_L_fun, step, bounds):
"""
Evaluate the Fisher matrix by MC sampling around the optimum
"""
x, log_L = self.sample_log_L(log_L_fun, x_0=x_0)
if self.trace is not None:
self.trace.on_eval_F_mcmc(x, log_L)
# This is already the covanriance, we need its inverse here
C = np.cov(x.T)
return -np.linalg.inv(C), C
def eval_F_sampling(self, x_0, log_L_fun, step, bounds):
"""
Sample a bunch of RVs around the optimum and fit a parabola
to obtain the error of RV.
"""
# Default step size is 1% of optimum values
if step is None:
step = 1.0e-2 * x_0
# TODO: what do we do with the original bounds?
nbounds = np.stack([x_0 - step, x_0 + step], axis=-1)
nbounds[..., 0] = np.where(bounds[..., 0] > nbounds[..., 0], bounds[..., 0], nbounds[..., 0])
nbounds[..., 1] = np.where(bounds[..., 1] < nbounds[..., 1], bounds[..., 1], nbounds[..., 1])
x = np.random.uniform(nbounds[..., 0], nbounds[..., 1], size=(500,) + x_0.shape)
log_L = np.empty(x.shape[:-1])
for ix in range(x.shape[0]):
log_L[ix] = log_L_fun(np.atleast_1d(x[ix]))
n = x_0.size
if n == 1:
p = np.polyfit(x.item(), log_L, 2)
return np.array([[2.0 * p[0]]]), np.array([[-0.5 / p[0]]])
else:
# Fit n-D quadratic formula
# Create the design matrix and solve the least squares problem
pf = PolynomialFeatures(degree=2)
X = pf.fit_transform(x - x_0)
p = np.linalg.solve(X.T @ X, X.T @ (log_L - np.min(log_L)))
# Construct the hessian from the p parameters
F = np.empty((n, n), dtype=x.dtype)
for pi, pw in zip(p[n + 1:], pf.powers_[n + 1:]):
idx = np.where(pw)[0] # Index of item in the Hessian
if idx.size == 1:
# Diagonal item:
F[idx[0], idx[0]] = 2 * pi
else:
# Mixed item
F[idx[0], idx[1]] = F[idx[1], idx[0]] = pi
return F, np.linalg.inv(-F)
#endregion
@staticmethod
def lorentz(x, a, b, c, d):
return a / (1 + (x - b) ** 2 / c ** 2) + d
def fit_lorentz(self, rv, y0):
"""
Fit a Lorentz function to the log-likelihood to have a good initial guess for RV.
"""
# Guess initial values from y0
p0 = [
np.max(y0),
rv[np.argmax(y0)],
0.5 * (rv[-1] - rv[0]),
y0.min() + 0.5 * (y0.max() - y0.min())
]
# Bounds
bb = [
(
0,
rv[0] - 1,
0.2 * (rv[-1] - rv[0]),
y0.min()
),
(
5 * np.max(y0),
rv[-1] + 1,
5.0 * (rv[-1] - rv[0]),
y0.min() + 4 * (y0.max() - y0.min())
)
]
pp, pcov = curve_fit(self.lorentz, rv, y0, p0=p0, bounds=bb)
return pp, pcov
def sample_rv_prior(self, rv_prior, bounds=None):
rv_0 = rv_prior.sample()
if bounds is not None:
if bounds[0] is not None:
rv_0 = max(rv_0, bounds[0])
if bounds[1] is not None:
rv_0 = min(rv_0, bounds[1])
return rv_0
def calculate_log_L(self, spectra, templates, rv, rv_prior=None, a=None):
"""
Calculate the logarithm of the likelihood at the given values of RV.
The function calls into the underlying correction model to calculate log L
and adds the constribution of the priors.
"""
if not isinstance(rv, np.ndarray):
rvv = np.atleast_1d(rv)
else:
rvv = rv.flatten()
rv_prior = rv_prior if rv_prior is not None else self.rv_prior
if self.trace is not None:
trace_state = TempFitTraceState()
pp_spec = self.preprocess_spectra(spectra)
# Calculate log L at each RV
log_L = np.full(rvv.shape, np.nan)
for i in range(rvv.size):
if self.trace is not None:
trace_state.reset()
# Pre-process each exposure in each arm and pass them to the log L calculator
# function of the flux correction or continuum fit model.
pp_temp = self.preprocess_templates(spectra, templates, rvv[i])
# Save everything to the trace
if self.trace is not None:
for arm in pp_spec:
for ei, (spec, temp) in enumerate(zip(pp_spec[arm], pp_temp[arm])):
trace_state.append(arm, spec, temp)
# Calculate log L
lp = self.correction_model.eval_log_L(pp_spec, pp_temp, a=a)
# Add the priors
# TODO: factor this into a function that can be overridden
lp += self.eval_prior(rv_prior, rvv[i])
log_L[i] = lp
if self.trace is not None:
self.trace.on_calculate_log_L(trace_state.spectra, trace_state.templates, rvv[i], lp)
log_L = np.reshape(log_L, np.shape(rv))
if isinstance(log_L, np.ndarray) and log_L.size == 1:
log_L = log_L.item()
return log_L
def calculate_coeffs(self, spectra, templates, rv):
"""
Evaluate the correction model parameters at the given RV
"""
pp_specs = self.preprocess_spectra(spectra)
pp_temps = self.preprocess_templates(spectra, templates, rv)
a = self.correction_model.calculate_coeffs(pp_specs, pp_temps)
return a
def guess_rv(self, spectra, templates, /, rv_bounds=(-500, 500), rv_prior=None, rv_steps=31, method='lorentz'):
"""
Given a spectrum and a template, make a good initial guess for RV where a minimization
algorithm can be started from.
Parameters
----------
spectra : dict of Spectrum or dict of list of Spectrum
Observed spectra
templates : dict of Spectrum
Synthetic stellar templates for each arm
rv_bounds : tuple
RV bounds to search for the guess
rv_prior : Distribution or callable
Prior distribution for the RV
rv_steps : int
Number of steps to sample the RV space
method : str
Method to use to guess the RV: 'lorentz' or 'max'
Returns
-------
ndarray, ndarray, float
RV grid, log likelihood values, guessed RV
"""
rv_bounds = rv_bounds if rv_bounds is not None else self.rv_bounds
rv_prior = rv_prior if rv_prior is not None else self.rv_prior
method = method if method is not None else 'lorentz'
rv = np.linspace(*rv_bounds, rv_steps)
log_L = self.calculate_log_L(spectra, templates, rv, rv_prior=rv_prior)
if method == 'lorentz':
# Mask out infs here in case the prior is very narrow
mask = (~np.isnan(log_L) & ~np.isinf(log_L))
if mask.sum() < 10:
raise Exception("Too few values to guess RV. Consider changing the bounds.")
pp, pcov = self.fit_lorentz(rv[mask], log_L[mask])
rv_guess = pp[1]
# The maximum of the Lorentz curve might be outside the bounds
if rv_bounds is not None and rv_bounds[0] is not None:
rv_guess = max(rv_guess, rv_bounds[0])
if rv_bounds is not None and rv_bounds[1] is not None:
rv_guess = min(rv_guess, rv_bounds[1])
if self.trace is not None:
self.trace.on_guess_rv(rv, log_L, rv_guess, self.lorentz(rv, *pp), 'lorentz', pp, pcov)
elif method == 'max':
rv_guess = rv[np.argmax(log_L)]
if self.trace is not None:
self.trace.on_guess_rv(rv, log_L, rv_guess, None, 'max', None, None)
else:
raise NotImplementedError()
return rv, log_L, rv_guess
def prepare_fit(self, spectra, templates, /,
rv_0=None, rv_bounds=(-500, 500), rv_prior=None, rv_step=None, rv_fixed=None):
rv_0 = rv_0 if rv_0 is not None else self.rv_0
rv_fixed = rv_fixed if rv_fixed is not None else self.rv_fixed
rv_bounds = rv_bounds if rv_bounds is not None else self.rv_bounds
rv_prior = rv_prior if rv_prior is not None else self.rv_prior
rv_step = rv_step if rv_step is not None else self.rv_step
if self.template_wlim is None:
self.determine_wlim(spectra, rv_bounds=rv_bounds)
if rv_0 is None and spectra is not None:
_, _, rv_0 = self.guess_rv(spectra, templates,
rv_bounds=rv_bounds, rv_prior=rv_prior,
method='max')
if rv_fixed:
logger.warning("No value of RV is provided, yet not fitting RV. The guessed value will be used.")
log_L_fun, pack_params, unpack_params, pack_bounds = self.get_objective_function(
spectra, templates,
rv_prior=rv_prior,
mode='rv'
)
if rv_0 is not None:
x_0 = pack_params(rv_0)[0]
else:
x_0 = None
# Step size for MCMC
if rv_step is not None:
steps = pack_params(rv_step)[0]
else:
steps = None
# Parameter bounds for optimizers, bounds is a list of tuples, convert to an array
bounds = pack_bounds(rv_bounds)
bounds = self.get_bounds_array(bounds)
return (rv_0, rv_fixed, rv_bounds, rv_prior, rv_step,
log_L_fun, pack_params, unpack_params, pack_bounds,
x_0, bounds, steps)
def fit_rv(self, spectra, templates,
rv_0=None, rv_bounds=(-500, 500), rv_prior=None, rv_fixed=None,
method='bounded', max_iter=None,
calculate_error=True):
"""
Given a set of spectra and templates, find the best fit RV by maximizing the log likelihood.
Spectra are assumed to be of the same object in different wavelength ranges, with multiple
exposures.
Parameters
----------
spectra : dict of Spectrum or dict of list of Spectrum
Observed spectra
templates : dict of Spectrum
Synthetic stellar templates for each arm
rv_0 : float
Initial guess for the RV
rv_bounds : tuple
RV bounds to limit the search for initial RV if not provided as well as
limits to the fit.
rv_prior : Distribution or callable
Prior distribution for the RV
rv_fixed : bool
If True, the RV is fixed and no optimization is performed.
method : str
Optimization method to use: 'bounded' or 'grid'
max_iter: int
Maximum number of iterations for the optimization
calculate_error : bool
If True, calculate the error of the RV from the Fisher matrix.
If no initial guess is provided, `rv_0` is determined automatically. If `rv_fixed` is
`True`, the radial velocity is not fitted but the best flux correction or continuum
model parameters are determined as if the provided `rv_0` was the best fit.
"""
assert isinstance(spectra, dict)
assert isinstance(templates, dict)
max_iter = max_iter if max_iter is not None else self.max_iter
# Initialize flux correction or continuum models for each arm and exposure
self.init_models(spectra, rv_bounds)
(rv_0, rv_fixed, rv_bounds, rv_prior, rv_step,
log_L_fun, pack_params, unpack_params, pack_bounds,
x_0, bounds, steps) = self.prepare_fit(spectra, templates,
rv_0=rv_0,
rv_fixed=rv_fixed,
rv_bounds=rv_bounds,
rv_prior=rv_prior)
if self.trace is not None:
self.trace.on_fit_rv_start(spectra, templates,
rv_0, rv_bounds, rv_prior, rv_step,
log_L_fun)
if rv_fixed:
# Only calculate the flux correction or continuum model coefficients at rv_0
results = self.fit_rv_fixed(spectra, templates, rv_0, rv_prior=rv_prior)
else:
# Optimize for RV
results = self.fit_rv_optimize(spectra, templates,
rv_0, rv_bounds, rv_prior, rv_step,
log_L_fun, pack_params, unpack_params, pack_bounds,
x_0, bounds, steps,
method, calculate_error)
return results
def fit_rv_fixed(self, spectra, templates,
rv_0, rv_prior):
# Calculate log_L in two steps, this requires passing around the flux correction or
# continuum fit parameters
# a_fit = self.calculate_coeffs(spectra, templates, rv_0)
# a_err = np.full_like(a_fit, np.nan)
# log_L_fit = self.calculate_log_L(spectra, templates, rv_0, rv_prior=rv_prior, a=a_fit)
# Calculate log_L in a single step, this won't provide the flux correction or
# continuum fit parameters
a_fit = None
a_err = None
log_L_fit = self.calculate_log_L(spectra, templates, rv_0, rv_prior=rv_prior)
results = TempFitResults(rv_fit=rv_0, rv_err=np.nan,
a_fit=a_fit, a_err=a_err,
cov=None, log_L_fit=log_L_fit)
return results
def fit_rv_optimize(self, spectra, templates,
rv_0, rv_bounds, rv_prior, rv_step,
log_L_fun, pack_params, unpack_params, pack_bounds,
x_0, bounds, steps,
method, calculate_error):
# Cost function
def llh(rv):
return -log_L_fun(pack_params(rv))
# Multivariate method
# out = minimize(llh, [rv0], method=method)
# Univariate method
# NOTE: scipy.optimize is sensitive to type of args
rv_bounds = tuple(float(b) for b in rv_bounds)
bracket = None
# if rv_bounds is not None and rv_bounds[0] < rv_0 and rv_0 < rv_bounds[1]:
# bracket = (rv_bounds[0], float(rv_0), rv_bounds[1])
# else:
# bracket = None
try:
if method == 'grid':
out = TempFit.minimize_gridsearch(llh, bounds=rv_bounds)
else:
out = minimize_scalar(llh, bracket=bracket, bounds=rv_bounds, method=method)
except Exception as ex:
raise ex
if out.success:
rv_fit = unpack_params(out.x)
lp = -out.fun
else:
raise Exception(f"Could not fit RV using `{method}`")
# Calculate the flux correction or continuum fit coefficients at best fit values
a_fit = self.calculate_coeffs(spectra, templates, rv_fit)
# Calculate the error from the Fisher matrix
if calculate_error:
_, C = self.calculate_F(spectra, templates,
rv_fit, rv_bounds=rv_bounds, rv_prior=rv_prior,
mode='rv', method='hessian')
with np.errstate(invalid='warn'):
rv_err = np.sqrt(C[-1, -1]) # sigma
else:
rv_err = None
C = None
if self.trace is not None:
# If tracing, evaluate the template at the best fit RV.
# TODO: can we cache this for better performance?
# Apply the correction model to the templates preprocessed to match each spectrum
tt = self.preprocess_templates(spectra, templates, rv_fit)
self.correction_model.apply_correction(spectra, tt, a_fit)
# TODO: pass in continuum model for plotting
# pass in covariance matrix
self.trace.on_fit_rv_finish(spectra, templates, tt,
rv_0, rv_fit, rv_err, rv_bounds, rv_prior, rv_step, False,
log_L_fun)
return TempFitResults(rv_fit=rv_fit, rv_err=rv_err,
a_fit=a_fit, a_err=np.full_like(a_fit, np.nan),
cov=C, log_L_fit=lp)
def randomize_init_params(self, spectra, rv_0=None, rv_bounds=None, rv_prior=None, rv_step=None, rv_fixed=None,
rv_err=None,
randomize=False, random_size=()):
rv_fixed = rv_fixed if rv_fixed is not None else self.rv_fixed
rv_bounds = rv_bounds if rv_bounds is not None else self.rv_bounds
rv_prior = rv_prior if rv_prior is not None else self.rv_prior
rv_step = rv_step if rv_step is not None else self.rv_step
# Generate an initial state for MCMC by sampling the prior randomly
if rv_0 is None or np.isnan(rv_0):
if rv_prior is not None:
rv = self.sample_rv_prior(rv_prior, rv_bounds)
else:
if self.rv_0 is not None:
rv = self.rv_0
else:
raise NotImplementedError()
else:
rv = rv_0
if randomize and not rv_fixed:
if rv_step is not None:
rv = rv + rv_step * (np.random.rand(*random_size) - 0.5)
else:
rv = rv * (1.0 + 0.05 * (np.random.rand(*random_size) - 0.5))
if rv_bounds is not None:
if rv_bounds[0] is not None:
rv = np.maximum(rv, rv_bounds[0])
if rv_bounds[1] is not None:
rv = np.minimum(rv, rv_bounds[1])
if rv_err is None or np.any(np.isnan(rv_err)):
if rv_step is not None:
rv_err = rv_step ** 2
else:
rv_err = (0.05 * np.mean(rv)) ** 2 + 1.0
return rv, rv_err
def run_mcmc(self, spectra, templates, *,
rv_0=None, rv_bounds=(-500, 500), rv_prior=None, rv_step=None, rv_fixed=None,
cov=None,
walkers=None, burnin=None, samples=None, thin=None, gamma=None):
"""
Given a set of spectra and templates, sample from the posterior distribution of RV.
If no initial guess is provided, an initial state is generated automatically.
"""
assert isinstance(spectra, dict)
assert isinstance(templates, dict)
walkers = walkers if walkers is not None else self.mcmc_walkers
burnin = burnin if burnin is not None else self.mcmc_burnin
samples = samples if samples is not None else self.mcmc_samples
thin = thin if thin is not None else self.mcmc_thin
gamma = gamma if gamma is not None else self.mcmc_gamma
# Initialize flux correction or continuum models for each arm and exposure
self.init_models(spectra, rv_bounds)
(rv_0, rv_fixed, rv_bounds, rv_prior, rv_step,
log_L_fun, pack_params, unpack_params, pack_bounds,
x_0, bounds, steps) = self.prepare_fit(spectra, templates,
rv_0=rv_0, rv_bounds=rv_bounds,
rv_prior=rv_prior, rv_step=rv_step,
rv_fixed=rv_fixed)
if bounds is not None and np.any((np.transpose(x_0) < bounds[..., 0]) | (bounds[..., 1] < np.transpose(x_0))):
raise Exception("Initial state is outside bounds.")
# We only have a single parameter, there's no need for Gibbs sampling
gibbs_blocks = [[ 0 ]]
mcmc = MCMC(log_L_fun, step_size=steps, gibbs_blocks=gibbs_blocks,
walkers=walkers, gamma=0.99)
# A leading dimension is required by the mcmc sampler in x_0
# res_x.shape: (num_vars, samples, walkers)
# res_lp.shape: (samples, walkers)
res_x, res_lp, accept_rate = mcmc.sample(x_0[None, ...], burnin, samples, gamma=gamma)
rv = unpack_params(res_x)
return TempFitResults(rv_mcmc=rv, log_L_mcmc=res_lp, accept_rate=accept_rate)
@staticmethod
def minimize_gridsearch(fun, bounds, nstep=100):
# Find minimum with direct grid search. For testing only
x = np.linspace(bounds[0], bounds[1], nstep)
# TODO: rewrite log_l function to take vectorized input
# raise NotImplementedError
# y = fun(x)
y = np.empty_like(x)
for i in range(x.size):
y[i] = fun(x[i])
mi = np.argmin(y)
class Result(): pass
out = Result()
out.success = True
out.x = x[mi]
return out
def calculate_rv_bouchy(self, spectra, templates, rv_0):
# Calculate a delta V correction by the method of Bouchy (2001)
# TODO: we might need the flux correction coefficients here
# this function depends on a flux correction model
a_0 = self.calculate_coeffs(spectra, templates, rv_0)
nom = 0
den = 0
sumw = 0
for arm in spectra:
if not isinstance(spectra[arm], list):
specs = [spectra[arm]]
else:
specs = spectra[arm]
for ei in range(len(specs)):
spec = self.process_spectrum(arm, ei, specs[ei])
temp = self.process_template(arm, templates[arm], spec, rv_0, diff=True)
if self.use_mask:
mask = ~spec.mask if spec.mask is not None else np.s_[:]
else:
mask = np.s_[:]
if isinstance(mask, np.ndarray):
# We are going to calculate the central difference of flux for
# each pixel, so dilate the mask here by 1 pixel in both directions
mask = binary_dilation(mask)
if isinstance(self.correction_model, FluxCorr) and self.correction_model.use_flux_corr:
# Evaluate the correction function
raise NotImplementedError()
basis = self.flux_corr_basis(spec.wave)
corr = np.dot(basis, a_0)
else:
corr = a_0
# Eq. 3
_, dAdl = self.diff_template(temp)
dV = (spec.flux - corr * temp.flux) / temp.wave / (corr * dAdl)
# Eq. 8
w = temp.wave**2 * (corr * dAdl)**2 / spec.flux_err**2
# Eq. 4 nominator and denominator
nom += np.sum(dV[mask] * w[mask])
den += np.sum(w[mask])
# Eq. 10 denominator
sumw += np.sum(w[mask])
# TODO: add trace function call
# Eq. 9 and Eq. 10
return 1e-3 * Physics.c * nom / den, 1e-3 * Physics.c / np.sqrt(sumw)
|
<?php
/**
* Sample implementation of the Custom Header feature
*
* You can add an optional custom header image to header.php like so ...
*
<?php the_header_image_tag(); ?>
*
* @link https://developer.wordpress.org/themes/functionality/custom-headers/
*
* @package nus
*/
/**
* Set up the WordPress core custom header feature.
*
* @uses nus_header_style()
* @uses nus_admin_header_style()
* @uses nus_admin_header_image()
*/
function nus_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'nus_custom_header_args', array(
'default-image' => '',
'default-text-color' => '000000',
'width' => 1000,
'height' => 250,
'flex-height' => true,
'wp-head-callback' => 'nus_header_style',
'admin-head-callback' => 'nus_admin_header_style',
'admin-preview-callback' => 'nus_admin_header_image',
) ) );
}
add_action( 'after_setup_theme', 'nus_custom_header_setup' );
if ( ! function_exists( 'nus_header_style' ) ) :
/**
* Styles the header image and text displayed on the blog
*
* @see nus_custom_header_setup().
*/
function nus_header_style() {
$header_text_color = get_header_textcolor();
/*
* If no custom options for text are set, let's bail.
* get_header_textcolor() options: Any hex value, 'blank' to hide text. Default: add_theme_support( 'custom-header' ).
*/
if ( get_theme_support( 'custom-header', 'default-text-color' ) === $header_text_color ) {
return;
}
// If we get this far, we have custom styles. Let's do this.
?>
<style type="text/css">
<?php
// Has the text been hidden?
if ( ! display_header_text() ) :
?>
.site-title,
.site-description {
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
}
<?php
// If the user has set a custom color for the text use that.
else :
?>
.site-title a,
.site-description {
color: #<?php echo esc_attr( $header_text_color ); ?>;
}
<?php endif; ?>
</style>
<?php
}
endif; // nus_header_style
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
样例
Example 1:
Input: [3, 8, 4]
Output: 8
Explanation: Just rob the second house.
Example 2:
Input: [5, 2, 1, 3]
Output: 8
Explanation: Rob the first and the last house.
挑战
O(n) time and O(1) memory.
class Solution:
"""
@param A: An array of non-negative integers
@return: The maximum amount of money you can rob tonight
"""
def houseRobber(self, A):
# write your code here
n = len(A)
if n == 0:
return 0
if n == 1:
return A[0]
f = [0] * (n+1)
f[1] = A[0]
for i in range(2, n+1):
f[i] = max(f[i-2] + A[i-1], f[i-1])
return f[n]
class Solution:
"""
@param A: An array of non-negative integers
@return: The maximum amount of money you can rob tonight
"""
def houseRobber(self, A):
# write your code here
n = len(A)
if n == 0:
return 0
if n == 1:
return A[0]
old = 0
now = A[0]
for i in range(2, n+1):
t = max(old + A[i-1], now)
old = now
now = t
return now
|
import React, { useCallback } from "react";
import { FlatList, StyleSheet, Text, Pressable } from "react-native";
import {
useNavigation,
NavigationProp,
CompositeNavigationProp,
} from "@react-navigation/native";
import { Poster } from "@components/Poster";
import { MAIN_STACK_ROUTES, paramsList } from "@navigators/MainStackNavigator";
import { LoadingState } from "./components/LoadingState";
import type { Movie } from "../../types/client";
export const MOVIE_LIST_TEST_ID = "movielist-test-id";
export const BUTTON_A11Y_LABEL = "movie button to:";
type CompositeNavigationPropNavigationProp = CompositeNavigationProp<
NavigationProp<paramsList, MAIN_STACK_ROUTES.BottomTabNavigation>,
NavigationProp<paramsList>
>;
type ListOfMoviesProps = {
data?: Movie[];
loading: boolean;
};
export const ListOfMovies = ({ data, loading }: ListOfMoviesProps) => {
const { navigate } = useNavigation<CompositeNavigationPropNavigationProp>();
const keyExtractor = useCallback((item: Movie) => {
return item.id;
}, []);
const handleClick = (id: string) => {
navigate(MAIN_STACK_ROUTES.MovieDetail, { id: id });
};
const renderItem = useCallback(
({ item: { id, title, poster_path } }: { item: Movie }) => (
<Pressable
style={styles.row}
onPress={() => handleClick(id)}
aria-label={`${BUTTON_A11Y_LABEL} ${title}`}
role="button"
>
<Poster style={styles.image} poster_path={poster_path} />
<Text style={styles.text}>{title}</Text>
</Pressable>
),
[handleClick],
);
if (loading) {
return <LoadingState />;
}
return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={keyExtractor}
testID={MOVIE_LIST_TEST_ID}
/>
);
};
const styles = StyleSheet.create({
row: {
flexDirection: "row",
marginTop: 10,
backgroundColor: "white",
marginHorizontal: 10,
alignItems: "center",
},
image: {
width: 70,
height: 100,
},
text: {
marginHorizontal: 10,
},
});
|
import { CustomError } from "../exceptions/baseException.js";
import { tryCatch } from "../utils/tryCatchWrapper.js";
import User from "../models/userModel.js";
import generateToken from "../utils/generateToken.js";
const authUser = tryCatch(async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (user && (await user.matchPassword(password))) {
generateToken(res, user._id);
res.status(200).json({
_id: user._id,
name: user.name,
email: user.email,
role: user.role,
mobile: user.mobile,
});
} else {
throw new CustomError("Invalid email or password", 401);
}
});
const login = tryCatch(async (req, res) => {
const authHeader = req.headers.authorization;
try {
const { email, password } = req.body; // Extracting email and password from request body
// Finding user by email
const user = await User.findOne({ email });
// Checking if user exists and password matches
if (user && (await user.matchPassword(password))) {
// Generating token for authenticated user
const token = generateToken(res, user._id);
// Sending user information in response
res.status(200).json({
message: "Login successful",
user: {
_id: user._id,
name: user.name,
email: user.email,
role: user.role,
mobile: user.mobile,
},
token: token,
});
} else {
res.status(401).json({ error: "Invalid email or password" });
}
} catch (error) {
next(error);
}
});
const registerUser = tryCatch(async (req, res, next) => {
const { name, email, mobile, password, role } = req.body;
const userExists = await User.findOne({ email });
if (userExists) {
throw new CustomError("User already exists", 400);
}
const user = await User.create({
name,
email,
mobile,
password,
role,
});
if (user) {
generateToken(res, user._id);
res.status(201).json({
_id: user._id,
name: user.name,
email: user.email,
role: user.role,
});
} else {
throw new CustomError("Invalid user data", 400);
}
});
const logoutUser = tryCatch(async (req, res) => {
res.clearCookie("jwt");
res.status(200).json({ message: "User logged out" });
});
//get user details
const getUserProfile = tryCatch(async (req, res, next) => {
const user = await User.findById(req.user._id);
if (user) {
res.status(200).json(user);
} else {
throw new CustomError("User not found", 404);
}
});
//get all user profiles
const getAllProfiles = tryCatch(async (_, res) => {
const users = await User.find({});
res.json(users);
});
//update profile
const updateUserProfile = tryCatch(async (req, res, next) => {
const user = await User.findById(req.user._id);
if (user) {
user.name = req.body.name || user.name;
user.email = req.body.email || user.email;
user.mobile = req.body.mobile || user.mobile;
if (req.body.password) {
user.password = req.body.password;
}
const updatedUser = await user.save();
res.status(200).json({
_id: updatedUser._id,
name: updatedUser.name,
email: updatedUser.email,
mobile: updatedUser.mobile,
});
} else {
res.status(404);
throw new CustomError("User not found");
}
});
const deleteUserProfile = tryCatch(async (req, res, next) => {
const user = await User.findById(req.user._id);
if (user) {
await User.deleteOne({ _id: user._id });
res.status(200).json({ message: "User profile deleted" });
} else {
res.status(404);
throw new CustomError("User not found");
}
});
const deleteUser = tryCatch(async (req, res, next) => {
const user = await User.findById(req.params.id);
if (user) {
await User.deleteOne({ _id: user._id });
res.status(200).json({ message: "User deleted" });
} else {
res.status(404);
throw new CustomError("User not found");
}
});
const userById = tryCatch(async (req, res) => {
const id = req.params.id;
const user = await User.findById(id).select("-password");
if (!user) throw new CustomError("User not Found.", 404);
console.log(user);
res.status(200).json({ user });
});
export {
authUser,
registerUser,
logoutUser,
getUserProfile,
getAllProfiles,
updateUserProfile,
deleteUserProfile,
deleteUser,
userById,
login,
};
|
"use client";
import React from "react";
import {
VerticalTimeline,
VerticalTimelineElement,
} from "react-vertical-timeline-component";
import "react-vertical-timeline-component/style.min.css";
import { CgWorkAlt } from "react-icons/cg";
import { FaReact } from "react-icons/fa";
import { LuGraduationCap } from "react-icons/lu";
const experiencesData = [
{
title: "Full Stack development Bootcamp, Udemy, London App Brewery",
location: "Remote",
description:
"Developed a full stack web application from scratch, including back-end services, front-end interface, and database, and developed a full stack web application with a modern user interface that improved userengagement by 10%",
icon: React.createElement(LuGraduationCap),
date: "2020 - June 2022",
},
{
title: "Backend Developer",
location: "Fiverr",
description:
"Develops, tests and deploys applications in cloud environments",
icon: React.createElement(CgWorkAlt),
date: "Oct, 2022 - Present",
},
{
title: "SEO Specialist",
location: "Upwork",
description:
"Developed and implemented successful SEO strategies to improve organic search rankings of my clients",
icon: React.createElement(CgWorkAlt),
date: "March,2023 - December, 2023",
},
{
title: "Full-Stack Developer",
location: "Anglaar Digital Agency",
description:
"Proven ability to build complex applications from scratch • ",
icon: React.createElement(FaReact),
date: "May, 2023 - present",
},
]
export default function Experience() {
return (
<section id="Experience" className="scroll-mt-28 mb-28 sm:mb-40">
<h2 className="text-center text-4xl font-bold text-white mt-4 mb-8 md:mb-12">
My Experience
</h2>
<VerticalTimeline lineColor="white">
{experiencesData.map((item, index) => (
<React.Fragment key={index}>
<VerticalTimelineElement
contentStyle={{
background:
"rgba(255, 255, 255, 0.05)",
boxShadow: "none",
border: "1px solid rgba(0, 0, 0, 0.05)",
textAlign: "left",
padding: "1.3rem 2rem",
color:'white'
}}
contentArrowStyle={{
borderRight:"0.4rem solid white",
}}
date={item.date}
icon={item.icon}
iconStyle={{
background:
"white",
fontSize: "1.5rem",
color:'black'
}}
>
<h3 className="font-semibold capitalize text-white">{item.title}</h3>
<p className="font-normal !mt-0 text-white">{item.location}</p>
<p className="!mt-1 !font-normal text-white">
{item.description}
</p>
</VerticalTimelineElement>
</React.Fragment>
))}
</VerticalTimeline>
</section>
);
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Answers; //새로 추가
use App\Models\Ages;
use Illuminate\Validation\Rule;
class answerFormController extends Controller
{
//
public function index()
{
$ages = Ages::orderBy('sort', 'asc')->get();
// dd($ages);
return view('answer.index', compact('ages'));
}
public function confirm(Request $request)
{
// 유효성 검사
$request->validate([
'fullname' => 'required|string|max:255',
'gender' => 'required|in:1,2',
'age_id' => 'required|exists:ages,sort',
'email' => 'required|email|max:255',
'feedback' => 'nullable|string|max:10000',
]);
// 사용자 입력 받아오기
$data = [
'fullname' => $request->input('fullname'),
'gender' => $request->input('gender'),
'age_id' => Ages::find($request->input('age_id'))->age,
'email' => $request->input('email'),
'is_send_email' => $request->input('is_send_email') ? '1' : '0',
'feedback' => nl2br($request->input('feedback')), // 개행을 <br>로 변환
];
session(['confirm_data' => $data]);
return view('answer.confirm', compact('data'));
}
public function finish(Request $request)
{
// 세션에서 데이터를 가져옴
$sessionData = $request->session()->get('confirm_data');
// 데이터베이스에 저장
$answer = new Answers();
$answer->fullname = $sessionData['fullname'];
$answer->gender = $sessionData['gender'];
$answer->age_id = Ages::where('age', $sessionData['age_id'])->value('sort');
$answer->email = $sessionData['email'];
$answer->is_send_email = $sessionData['is_send_email'] == '수신 동의함' ? 1 : 0;
$answer->feedback = $sessionData['feedback'];
$answer->save();
// dd($answer);
// 세션에서 데이터를 제거
$request->session()->forget('confirm_data');
// Finish 뷰를 반환
return redirect()->route('answer.index')->with('success', '입력이 완료되었습니다.');
}
public function show(){
return view('answer.show');
}
public function system(Request $request)
{
$query = Answers::query();
// 이름 검색어가 전달되었을 때만 적용
if ($request->has('name')) {
$name = $request->input('name');
$query->where('fullname', 'like', '%' . $name . '%');
}
$answers = $query->paginate(10); // 한 페이지당 10개씩 보이게 설정
// Gender와 Age 데이터를 불러오기
$genderMap = ['1' => '남자', '2' => '여자'];
// Ages 모델에서 sort 값을 기준으로 age를 가져오기
$agesData = Ages::pluck('age', 'sort')->all();
return view('answer.system', compact('answers', 'genderMap', 'agesData'))
->with('name', $request->input('name'))
->with('answers', $answers->appends($request->except('page')));
}
}
|
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<section id="usuarios" class="py-4 mb-4 bg-light">
<div class="container">
<div class="row">
<div class="col-md-5">
<div class="card mb-3">
<div class="card-header bg-primary text-white">
<h4>Parametros de busqueda</h4>
</div>
<form action="${pageContext.request.contextPath}/ServletControlador?accion=consultar"
method="POST">
<div class="mx-2 py-2 mb-2">
<button class="btn btn-primary" type="submit">Consultar</button>
<a href="${pageContext.request.contextPath}/ServletControlador?accion=resetear"
class="btn btn-primary" type="reset">Limpiar
</a>
</div>
<div class="card-body">
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" class="form-control" name="nombre" required>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-7">
<div class="card mb-6">
<div class="card-header bg-primary text-white">
<h4>Listado de Usuarios</h4>
</div>
<div class="mx-2 py-2 mb-2">
<a href="${pageContext.request.contextPath}/ServletControlador?accion=crear"
class="btn btn-primary">
Crear
</a>
</div>
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>#</th>
<th>ID Rol</th>
<th>Nombre</th>
<th>Activo</th>
<th></th>
</tr>
</thead>
<tbody>
<!-- Iteramos cada elemento de la lista de usuarios-->
<c:forEach var="usuario" items="${usuarios}" varStatus="status">
<tr>
<td>${usuario.idUsuario}</td>
<td>${usuario.idRol}</td>
<td>${usuario.nombre}</td>
<td>${usuario.activo}</td>
<td>
<a href="${pageContext.request.contextPath}/ServletControlador?accion=visualizar&idUsuario=${usuario.idUsuario}"
class="btn btn-secondary">Ver
</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
<section class="py-4 mb-4 bg-light">
<div class="container mb-3">
<div class="row">
<div class="col-md-9">
<div class="card">
<div class="card-header bg-primary text-white">
<h4>Informacion de Usuario</h4>
</div>
<form action="${pageContext.request.contextPath}/ServletControlador?accion=${funcionGuardar eq 'guardar' ? 'insertar' : 'modificar&idUsuario='}${usuario.idUsuario}"
method="POST" class="was-validated">
<div class="mx-2 py-2 mb-2">
<button class="btn btn-primary" type="submit" ${habilitar eq 'si' ? '' : 'disabled' }>Guardar</button>
<a data-role="button" type="button" href="${pageContext.request.contextPath}/ServletControlador?accion=editar&idUsuario=${usuario.idUsuario}"
class="btn btn-primary" ${ver eq 'si' ? '' : 'style="pointer-events: none; background-color:#62A1FE"'}>Editar
</a>
<a data-role="button" type="button" href="${pageContext.request.contextPath}/ServletControlador?accion=eliminar&idUsuario=${usuario.idUsuario}"
class="btn btn-primary" ${ver eq 'si' ? '' : 'style="pointer-events: none; background-color:#62A1FE"'}>Eliminar
</a>
</div>
<div class="card-body">
<div class="form-group">
<label for="id">Id</label>
<input type="number" class="form-control" name="id" required value="${usuario.idUsuario}"
readonly="readonly">
</div>
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" class="form-control" name="nombre" required value="${usuario.nombre}"
${habilitar eq 'si' ? '' : 'disabled' }>
</div>
<div class="form-group">
<label for="rol">Rol</label>
<select class="form-select" name="rol" aria-label="Default select example" required value="${usuario.idRol}"
${habilitar eq 'si' ? '' : 'disabled' }>
<option >Open this select menu</option>
<option ${rolSelect eq 'administrador' ? 'selected' : '' } value="1" >Administrador</option>
<option ${rolSelect eq 'auditor' ? 'selected' : '' } value="2" >Auditor</option>
<option ${rolSelect eq 'auxiliar' ? 'selected' : '' } value="3" >Auxiliar</option>
</select>
</div>
<div class="form-group">
<label for="activo" >Activo</label>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="activo" id="inlineRadio1" value="S"
${habilitar eq 'si' ? '' : 'disabled'} ${checkbox eq 'si' ? 'checked="checked"' : '' }>
<label class="form-check-label" for="activo">S</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="activo" id="inlineRadio2" value="N"
${habilitar eq 'si' ? '' : 'disabled'} ${checkbox eq 'no' ? 'checked="checked"' : '' }>
<label class="form-check-label" for="activo" >N</label>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
|
import { Route, Routes, json } from "react-router-dom"
import { About, Home, Comments, Login } from "./Pages"
import { Edit } from "./Pages/Edit"
import { NewFeedback } from "./Pages/NewFeedback"
import "./index.css"
import { Private, Public } from "./components/Routes"
import { Admin } from "./components/Admin"
import { useEffect } from "react"
import { useDispatch } from "react-redux"
import { userAction } from "./store/users/users.slice"
function App() {
let dispatch = useDispatch()
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(json => {
dispatch(userAction.setUser(json))
})
}, [])
return (
<>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/" element={<Public />} />
<Route path="/comments" element={<Comments />} />
<Route path="/about" element={<About />} />
<Route path="/add" element={<Edit />} />
<Route path="/edit" element={<NewFeedback />} />
<Route path="/login" element={<Login />} />
<Route path="/" element={<Private />} />
<Route path="/admin" element={<Admin />} />
</Routes>
</>
)
}
export default App
|
import { Bin } from "@rbxts/bin";
import { deepCopy } from "@rbxts/object-utils";
import Signal from "@rbxts/signal";
import { SupportedAttributeTypes } from "types/roblox";
/**
* Simple attribute management system
*
* I was supposed to use my own attributes package, but it wasn't suited
* for my needs.
*/
export class Attributes<T extends Record<string, SupportedAttributeTypes> | {}> {
private attributes = new Map<keyof T, T[keyof T]>();
private bin = new Bin();
private connection?: RBXScriptConnection;
private observantsBin = new Bin();
private isBusy = false;
public readonly changed = new Signal<(key: keyof T, value: T[keyof T] | undefined) => void>();
/** Creates a new attribute management class */
public constructor(private instance: Instance) {
// setting it up
this.bin.add(this.changed);
this.connection = instance.AttributeChanged.Connect(() => {
// we don't need to specify what attribute changed
this.onAttributesChanged();
});
this.bin.add(this.observantsBin);
this.bin.add(() => {
// making sure it is connected
if (this.connection !== undefined) {
this.connection.Disconnect();
this.connection = undefined;
}
});
// reload attributes
this.onAttributesChanged();
}
/**
* Sets the current instance of the class
*
* **NOTE**: It won't wipe the entire attributes but it will
* override the attributes from the new instance.
*
* If `wiped` parameter is enabled, the last instance will
* be definitely wiped.
* @param instance Instance to replace with
* @param wiped Optional parameter, it allows to wipe the entire attributes of the last instance
*/
public setInstance(instance: Instance, wiped?: boolean) {
// making sure that instance isn't the same
if (instance === this.instance) {
warn("Attempt to change instance with the same instance object");
return;
}
// copy the entire attributes map
const copied = deepCopy(this.attributes);
// destroy the connection, because we don't need it
this.connection?.Disconnect();
this.connection = undefined;
// wipe all of the observants
this.observantsBin.destroy();
// wipe the entire attributes if neccessary
if (wiped) {
this.wipe();
}
// replacing instance
this.instance = instance;
this.connection = instance.AttributeChanged.Connect(() => {
// we don't need to specify what attribute changed
this.onAttributesChanged();
});
// override the attributes table
this.isBusy = true;
for (const [key, value] of copied) {
this.set(key, value);
}
this.isBusy = false;
}
private onAttributesChanged() {
// making sure it is not busy (when nuking)
if (this.isBusy) return;
// get the entire attributes from instance member
const attributes = this.instance.GetAttributes() as Map<keyof T, T[keyof T]>;
const last_attributes = deepCopy(this.attributes);
// replacing the entire attributes table
this.attributes = attributes;
// checking for any changes
for (const [key, old_value] of last_attributes) {
const new_value = attributes.get(key);
if (new_value !== old_value) {
this.changed.Fire(key, new_value);
}
}
}
/**
* Deletes the attribute
* @param key Attribute to delete
*/
public delete<K extends keyof T>(key: K) {
// to avoid issues with the set method and probably get an update for that
this.instance.SetAttribute(key as string, undefined);
}
/**
* Observes any changes to the attribute
* @param key Attribute to observe with
* @param callback This function will run when an attribute is changed
*/
public observe<K extends keyof T>(key: K, callback: (new_value: T[K] | undefined) => void) {
let conn: RBXScriptConnection;
// eslint-disable-next-line prefer-const
conn = this.changed.Connect((updated_key, new_value) => {
if (updated_key === key) {
callback(new_value as T[K] | undefined);
}
});
this.bin.add(conn);
return conn;
}
/**
* Sets the attribute to a desired value
* @param key Attribute to set with the value
* @param value Value to replace with.
*/
public set<K extends keyof T>(key: K, value: T[K]) {
// avoid sudden same value overrides
if (this.attributes.get(key) === value) return;
this.instance.SetAttribute(key as string, value);
}
/** Copies and gets a local copy of attributes table */
public getAll(): Map<keyof T, T[keyof T] | undefined> {
return deepCopy(this.attributes);
}
/**
* Tries to get the attribute
* @param key Atttribute to get with
*/
public get<K extends keyof T>(key: K) {
return this.attributes.get(key);
}
/** Wipes the entire attributes table */
public wipe() {
this.isBusy = true;
// nuke it, with a bomb!
for (const [key] of this.attributes) {
this.delete(key);
}
this.isBusy = false;
}
/**
* Destroys the class
* @param wipe Optional, it will destroy upon destroying the class
*/
public destroy(wipe?: boolean) {
if (wipe === true) {
this.wipe();
}
this.bin.destroy();
}
}
|
-------------- Ejercicio 1 -----------------
-- Definir sin usar recursión la función
-- filtrarPares :: [[(Int,Int)]] -> [[(Int,Int)]] que, dada una lista de listas de pares de enteros,
-- filtra los pares cuya suma es mayor a 0.
-- Ej: filtrarPares [[(1,-1)], [(-3,2),(1,5)], [(0,1),(2,-1)]] ~> [[], [(1,5)], [(0,1),(2,-1)]].
-------------- Ejercicio 2 -----------------
-- Definir, usando el esquema de fold adecuado, la función
-- restas :: [Int] -> Int que, dada una lista de enteros,
-- devuelve la resta de todos ellos asociada a derecha.
-- Ej: restas [1,2,3,4] ~> 1 - (2 - (3 - 4))
-------------- Ejercicio 3 -----------------
data Nat = Zero | Succ Nat deriving Show
-- Definir la función restaTruncada :: Nat -> Nat -> Nat
-- que dados dos naturales n y m devuelve la resta n-m si n es mayor que m,
-- y devuelve Zero en otro caso.
--Ej: restaTruncada (Succ (Succ Zero)) (Succ Zero) ~> Succ Zero
-- restaTruncada (Succ Zero) (Succ (Succ Zero)) ~> Zero
-------------- Ejercicio 4 -----------------
data Arbol a = Hoja a | Nodo a (Arbol a) (Arbol a)
foldA :: (a -> b) -> (a -> b -> b -> b) -> Arbol a -> b
foldA f _ ( Hoja x) = f x
foldA f g ( Nodo x izq der) = g x ( foldA f g izq ) ( foldA f g der)
-- a) Definir, sin usar recursión explícita, una función esNodoInterno :: Int -> Arbol Int -> Bool
-- que devuelve True sii el entero está en algún nodo que no es una hoja.
-- Ej: esNodoInterno 2 (Nodo 1 (Nodo 2 (Hoja 0) (Hoja 3)) (Hoja (-3))) ~> True
-- esNodoInterno 3 (Nodo 1 (Nodo 2 (Hoja 0) (Hoja 3)) (Hoja (-3))) ~> False
-- b) Definir, sin usar recursión explícita, una función pasarALista :: Arbol Int -> [Int]
-- que devuelve la lista de todos los elementos positivos en un árbol de números enteros.
-- Ej: pasarALista (Nodo 1 ( Nodo 2 ( Hoja 0) ( Hoja 5)) ( Hoja (-3))) ~> [1,2,5]
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>IFE JavaScript Task 01</title>
</head>
<body>
<label>请输入北京今天空气质量:<input id="aqi-input" type="text"></label>
<button id="button">确认填写</button>
<div>您输入的值是:<span id="aqi-display">尚无录入</span></div>
<div><span id="validation"></span></div>
<script type="text/javascript">
(function() {
/*
在注释下方写下代码
给按钮button绑定一个点击事件
在事件处理函数中
获取aqi-input输入的值,并显示在aqi-display中
*/
const btn = document.getElementById('button');
const aqiInput = document.getElementById('aqi-input');
const aqiDisplay = document.getElementById('aqi-display');
const validator = document.getElementById('validation');
// 获取aqi-input输入的值,并进行格式检查,
// 检查通过则将输入值显示在aqi-display中
// 不通过则输出提示文字
function getAqi(){
const strInput = aqiInput.value;
validator.textContent = '';
if(strInput.match(/^[0-9]+$/)){
aqiDisplay.textContent = strInput;
aqiInput.value = '';
} else{
aqiInput.focus();
aqiInput.value = '';
validator.textContent = '请输入正确格式(数字)!';
}
}
// 添加点击事件
function getAqiByClick(){
btn.addEventListener('click', () => {
getAqi();
})
};
// 添加键盘Enter提交事件
function getAqiByEnter(){
aqiInput.addEventListener('keyup', (e) => {
e.preventDefault();
if(e.keyCode === 13){
getAqi();
}
})
};
getAqiByClick();
getAqiByEnter();
})();
</script>
</body>
</html>
|
$un-color: #333333;
$de-color: #BBACC1;
$tr-color: #F1DEDE;
@import url('https://fonts.googleapis.com/css2?family=Gravitas+One&family=Inter:wght@400;900&display=swap');
body{
display: grid;
grid-template-columns: repeat(2, calc(90% / 2));
grid-column-gap: 0;
grid-row-gap: 5vh;
justify-content: center;
justify-items: center;
font-family: 'Inter';
font-style: normal;
.header {
grid-area: 1 / 1 / 2 / 3;
width: 100%;
display: flex;
justify-content: space-between;
flex-direction: row;
align-items: center;
.logo{
color: $un-color;
font-family: 'Gravitas One';
font-style: normal;
font-weight: 400;
font-size: 60px;
line-height: 76px;
letter-spacing: -10px;
}
nav{
position: relative;
width: 50px;
height: 35px;
display: flex;
justify-content: space-between;
font-weight: 400;
font-size: 17px;
line-height: 21px;
color: $un-color;
cursor: pointer;
&:hover{
.mobile{
width:10px;
&::before{
width:25px;
}
&::after{
width:50px;
}
}
}
.mobile{
position: absolute;
width: 50px;
height: 5px;
right: 0;
top: 0px;
background: $un-color;
transition: all 0.5s ease;
&:before{
content: '';
position: absolute;
width: 40px;
height: 5px;
right: 0;
top: 15px;
background: $un-color;
transition: all 0.5s ease;
}
&:after{
content: '';
position: absolute;
width: 20px;
height: 5px;
right: 0;
top: 30px;
background: $un-color;
transition: all 0.5s ease;
}
}
a{
all: unset;
display: none;
font-weight: 400;
font-size: 17px;
line-height: 21px;
text-decoration: none;
position: relative;
cursor: pointer;
&:after{
width: 0%;
left: 50%;
height: 0.5vh;
content: " ";
position: absolute;
background: #333;
bottom: -1vh;
transition: all 0.5s ease;
}
&:hover{
&::after{
width: 110%;
left: -5%;
}
}
}
}
}
.news {
grid-area: 2 / 1 / 3 / 3;
width: 100%;
.img_n{
img{
width: 100%;
}
}
.content{
h1{
font-weight: 900;
font-size: 60px;
line-height: 60px;
color: $un-color;
}
.s_content{
p{
font-weight: 400;
font-size: 15px;
line-height: 25px;
}
button{
all: unset;
background: $de-color;
border-radius: 50px;
width: 202px;
height: 53px;
font-weight: 700;
font-size: 17px;
line-height: 25px;
text-align: center;
letter-spacing: 2px;
text-transform: uppercase;
color: $tr-color;
}
}
}
}
.actu-l{
grid-area: 3 / 1 / 4 / 3;
background-color: $un-color;
color: #ffffff;
width: 90%;
padding: 0 5%;
h1{
color: $de-color;
font-weight: 900;
font-size: 40px;
line-height: 60px;
}
.content{
h4{
font-weight: 900;
font-size: 19px;
line-height: 25px;
text-transform: capitalize;
color: $tr-color;
}
p{
font-weight: 400;
font-size: 15px;
line-height: 25px;
}
}
}
.actu-s{
grid-area: 4 / 1 / 5 / 3;
width: 100%;
.actu-i{
width: 100%;
display: flex;
margin: 5% 0;
img{
width: 30%;
height: auto;
}
.content{
display: flex;
flex-direction:column;
margin-left: 5%;
width: 100%;
h2{
margin: 5%;
font-weight: 900;
font-size: 31px;
line-height: 25px;
letter-spacing: 2px;
text-transform: uppercase;
color: $un-color;
}
h4{
margin: 5%;
font-weight: 900;
font-size: 19px;
line-height: 25px;
text-transform: capitalize;
color: $de-color;
}
p{
margin: 5%;
font-weight: 400;
font-size: 15px;
line-height: 25px;
color: #000000;
}
}
}
}
}
@for $i from 1 through 3 {
.actu-s .actu-i:nth-child(#{$i}) h2::after{
content: "0"+$i;
}
// .actu-l .content:nth-child(#{$i}):after{
// content: "";
// }
}
@media screen and (min-width: 1024px) {
body{
max-width: 100vw;
display: grid;
justify-items: center;
grid-template-columns: repeat(3, 30%);
// grid-template-rows: repeat(3, 1fr);
grid-column-gap: 2.5%;
grid-row-gap: 0px;
justify-items: center;
justify-content: center;
.header{
grid-area: 1 / 1 / 2 / 4;
height: 100px;
nav {
height: initial;
width: 40vw;
cursor: initial;
.mobile{
display: none;
}
a{
display: initial;
}
}
}
.news{
.img_n{
height: 45vh;
overflow: hidden;
img{
transform: translateY(-20%);
}
}
.content{
display: flex;
flex-wrap: wrap;
h1{
width: 50%;
}
.s_content{
width: 50%;
display: flex;
flex-direction: column;
justify-content: center;
}
}
grid-area: 2 / 1 / 3 / 3;
}
.actu-l{
grid-area: 2/3/3/4;
height: 100%;
}
.actu-s{
grid-area: 3 / 1 / 4 / 4;
display: flex;
}
}
}
|
<template>
<div>
<Navbar></Navbar>
<BreadCrumb></BreadCrumb>
<Container>
<el-container>
<el-aside class="aside">
<CenterSlider></CenterSlider>
</el-aside>
<el-main>
<div class="title-wrap" v-if="title">
<div class="title">{{ title }}</div>
</div>
<slot></slot>
</el-main>
</el-container>
</Container>
<Footer></Footer>
</div>
</template>
<script lang="ts" setup name="CenterWrap">
interface IProps {
title: string;
}
const props = withDefaults(defineProps<IProps>(), {
title: ''
});
</script>
<style lang="scss" scoped>
.aside {
width: 170px;
}
.title-wrap {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
.title {
font-weight: 700;
font-size: 20px;
}
}
</style>
|
Architecture
The OCDS Data Review tool comprises two main parts, which are documented here.
* cove-ocds (`this repository <https://github.com/open-contracting/cove-ocds>`_): a web application which makes light use of Django components.
* lib-cove-ocds (`open-contracting/lib-cove-ocds <https://github.com/open-contracting/lib-cove-ocds>`_): a library containing most of the functions for performing validation and transformation on OCDS data.
cove-ocds
---------
``cove_ocds/lib`` contains OCDS data specific exceptions (errors generated by invalid data or input), as well as additional functions for OCDS Show (the JavaScript data explorer).
``tests/`` also contains fixtures for testing, and the tests themselves; templates and related static files; code for the CLI version of the DRT; and locale files for translations.
``cove_ocds/views.py`` does most of the heavy lifting of taking an input file from the web interface and carrying out the various validation checks and conversions, then piping the output back to the right templates.
``cove_project/`` contains the Django components (settings, URL paths, server).
lib-cove-ocds
-------------
lib-cove-ocds contains OCDS data specific functions, but in a way that means they can be reused by other software and scripts without having to import the whole of the DRT to do so. It includes the SchemaOCDS object. Most of the validation checks for OCDS data are here.
lib-cove-ocds produces results in the form of dictionaries with meaningful keys. cove-ocds is responsible for mapping these keys onto a suitable UI. It's worth noting that cove-ocds is not the only tool that consumes the output of lib-cove-ocds. Different tools can produce the best UI for their particular context, so any UI or display work is done in the tool and not in the underlying library. This also means that the respective UIs can be translated or localized independently, according to the needs or usage of the tools. Having machine readable output from the library also means that we can take a database of output and easily parse it to create statistics about results or errors, etc.
External libraries
------------------
The OCDS Data Review Tool is just one manifestation of software historically known as 'CoVE' (Convert, Validate, Explore). Instances of CoVE exist for other standards as well as OCDS. We modularize and reuse code where possible, so as a result the DRT has dependencies on external libraries related to CoVE:
* lib-cove (`opendataservices/lib-cove <https://github.com/opendataservices/lib-cove>`_): contains functions and helpers that may be useful for data validation and review, regardless of the particular data standard.
* lib-cove-web (`opendataservices/lib-cove-web <https://github.com/opendataservices/lib-cove-web>`_): provides a barebones Django configuration, and baseline CSS, JS and templates that are common for all CoVE instances. It is also a place for common functions relating to presentation or display of data or output. Any templates edited here typically affect all CoVE instances. Sometimes this is useful, but for OCDS-only changes, templates can be overridden in cove-ocds. This and cove-ocds are the only places where frontend output and translatable strings should be.
* flatten-tool (`opendataservices/flatten-tool <https://github.com/opendataservices/flatten-tool>`_): a general purpose library for converting data between JSON and CSV/XLS formats. While not CoVE-specific, it is listed here because it is a specialized tool of which the DRT makes heavy use.
Config
------
Some configuration variables are set in ``COVE_CONFIG``, found in ``cove_project/settings.py``.
* ``app_name``, ``app_verbose_name``, ``app_strapline``, ``support_email``: set human readable strings for the DRT that can be reused in templates etc.
* ``app_base_template``, ``input_template``, ``input_methods``: set the templates for the landing page.
* ``schema_version_choices`` (``version: (display, url, tag)``), ``schema_codelists``: point to JSON schema files that the DRT uses for validating and converting data. Since there is more than one version of the Open Contracting Data Standard, this lets the user choose which version of the scheme they are validating against.
* ``root_list_path``, ``root_id``: set so the DRT knows which key to use as the root of the data, and which key to use as the main identifier when parsing the data. These, along with ``convert_titles`` are passed to the flattentool library.
Path through the code
---------------------
1. The input form on the landing page can be found in the ``input`` template (``cove_ocds/templates``). The OCDS DRT overrides the default input template from lib-cove-web so it can be customized compared to other instances of CoVE. This override is set using the ``input_template`` setting in ``COVE_CONFIG`` (see above).
2. Submitting the form calls the `explore_ocds` function (``cove_ocds/views.py``).
* This checks for basic problems with the input file, and adds metadata, using ``explore_data_context`` from lib-cove-web.
* It then performs OCDS specific JSON checks, if the input data is JSON.
* And then schema-specific OCDS checks, depending on the version specified, using ``SchemaOCDS`` and ``common_checks`` from lib-cove-ocds. Functions from lib-cove-ocds also takes care of handling any extension data included in the input. lib-cove-ocds calls on lib-cove to perform schema validation that is not specific to OCDS, using JSON Schema and JSONRef, as well as common things like checking for duplicate identifiers.
* lib-cove-ocds runs additional checks, which are basic data quality checks outside of the OCDS schema.
* The results of the various stages of validation are added to the context so they can be displayed on the frontend. The JSON schema error messages are currently set in lib-cove and OCDS schema specific messages are set in lib-cove-ocds or in this repo (``cove_ocds/lib/exceptions.py``).
* It uses flattentool to convert the input JSON data into XLSX, or vice versa.
3. The results of the validation, as well as some basic statistics on the data, are output to the ``explore_record`` and ``explore_release`` html templates in ``cove_ocds/templates``.
|
import * as chai from 'chai';
import {generateTokens, getAllTagsReworked} from './token.mjs';
import 'mjs-mocha';
const {assert} = chai.default;
describe('token', () => {
it('generateTokens generates list of all possible tokens', () => {
const tokensConfiguration = {
div: [{'display': ['flex']}, {'flex-direction': ['row', 'collumn']}],
};
const expectedResults = [
'">',
'<div style="',
'display:flex;',
'flex-direction:row;',
'flex-direction:collumn;',
'</div>',
];
const result = generateTokens(tokensConfiguration);
assert.sameMembers(result, expectedResults, 'sameMember');
});
it('generateTokens generates list of all with single value tokens', () => {
const tokensConfiguration = {
strong: [{'margin': ['5px']}],
};
const expectedResults = [
'">',
'<strong style="',
'margin:5px;',
'</strong>',
];
const result = generateTokens(tokensConfiguration);
assert.sameMembers(result, expectedResults, 'sameMember');
});
it('generateTokens generates list of all posible html tags', () => {
const tokensConfiguration = {
div: [
{'a': ['b', 'c']},
{'d': ['e', 'g', 'h']},
{'j': ['k', 'l']},
],
};
const expectedResults = [
'<div style="a:b;"></div>',
'<div style="a:c;"></div>',
'<div style="a:b; d:e;"></div>',
'<div style="a:b; d:g;"></div>',
'<div style="a:b; d:h;"></div>',
'<div style="a:c; d:e;"></div>',
'<div style="a:c; d:g;"></div>',
'<div style="a:c; d:h;"></div>',
'<div style="a:b; d:e; j:k;"></div>',
'<div style="a:b; d:e; j:l;"></div>',
'<div style="a:b; d:g; j:k;"></div>',
'<div style="a:b; d:g; j:l;"></div>',
'<div style="a:b; d:h; j:k;"></div>',
'<div style="a:b; d:h; j:l;"></div>',
'<div style="a:c; d:e; j:k;"></div>',
'<div style="a:c; d:e; j:l;"></div>',
'<div style="a:c; d:g; j:k;"></div>',
'<div style="a:c; d:g; j:l;"></div>',
'<div style="a:c; d:h; j:k;"></div>',
'<div style="a:c; d:h; j:l;"></div>',
'<div style="d:e;"></div>',
'<div style="d:g;"></div>',
'<div style="d:h;"></div>',
'<div style="d:e; j:k;"></div>',
'<div style="d:g; j:k;"></div>',
'<div style="d:h; j:k;"></div>',
'<div style="d:e; j:l;"></div>',
'<div style="d:g; j:l;"></div>',
'<div style="d:h; j:l;"></div>',
'<div style="j:k;"></div>',
'<div style="j:l;"></div>',
];
const result = getAllTagsReworked(tokensConfiguration)
.map((callback) => callback(''));
assert.sameMembers(result, expectedResults, 'sameMember');
});
});
|
#pragma once
#include "repo.h"
#include "Observer.h"
class UserService {
UserRepository* userRepo;
public:
UserService(Subject* gs, UserRepository* ur) : userRepo(ur) {}
vector<User> get_all() {
return userRepo->get_all();
}
};
class QuestionService {
QuestionRepository* questionRepo;
AnswerRepository* answerRepo;
Subject* globalSubject;
public:
QuestionService(Subject* gs, QuestionRepository* ur, AnswerRepository* ar) : globalSubject(gs), questionRepo(ur), answerRepo(ar) {}
vector<Question> get_all() {
return questionRepo->get_all();
}
vector<Question> get_all_sorted() {
auto all = questionRepo->get_all();
sort(all.begin(), all.end(), [&](Question q1, Question q2) {
return get_answers_for(q1).size() > get_answers_for(q2).size();
});
return all;
}
vector<Answer> get_answers_for(Question q) {
auto all = answerRepo->get_all();
vector<Answer> out;
copy_if(all.begin(), all.end(), back_inserter(out), [&](Answer a) { return a.getQuestionId() == q.getId(); });
return out;
}
void add(string text, User user) {
int id = questionRepo->get_all().size() + 1;
Question q{ id, text, user.getName() };
questionRepo->add(q);
globalSubject->notifyAll();
}
};
class AnswerService {
AnswerRepository* answerRepo;
Subject* globalSubject;
public:
AnswerService(Subject* gs, AnswerRepository* ur) :globalSubject(gs), answerRepo(ur) {}
vector<Answer> get_all() {
return answerRepo->get_all();
}
void add(Question q, User user, string text) {
int id = answerRepo->get_all().size() + 1;
answerRepo->add(Answer{
id,
q.getId(),
text,
user.getName(),
0
});
globalSubject->notifyAll();
}
void updateVoteCount(Answer a, int newVotes) {
a.setVotes(newVotes);
answerRepo->update(a);
globalSubject->notifyAll();
}
};
|
package hello.springmvc1servlet.web.springmvc.v1;
import hello.springmvc1servlet.domain.member.Member;
import hello.springmvc1servlet.domain.member.MemberRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
public class SpringMemberListControllerV1 {
private MemberRepository memberRepository = MemberRepository.getInstance();
@RequestMapping("springmvc/v1/members")
public ModelAndView process(){
List<Member> members = memberRepository.findAll();
// ModelAndView 객체에 모델과 뷰 정보 담아서 반환
ModelAndView mv = new ModelAndView("members"); // 모델 뷰 객체 생성, 뷰 이름 저장
mv.addObject("members", members); // Model 정보 저장
return mv;
}
}
|
const Config = require('config');
const tar = require('tar-stream');
const tarFs = require('tar-fs');
const sha256 = require('js-sha256');
const sha256File = require('sha256-file');
const Path = require('path');
const Handlebars = require('handlebars');
const fs = require('fs');
const fse = require('fs-extra');
const chalk = require('chalk');
function generateContent(context, source) {
const buf = fs.readFileSync(Path.resolve(__dirname, source));
const middleware = Handlebars.compile(buf.toString());
const out = middleware(context);
return out;
}
function saveFile(context, filename, content) {
const p = `${context.outputFolder}/${filename}`;
fse.outputFileSync(p, content);
console.log(`output: ${filename}`);
}
function createResource(context, resourcePath, outResourcePath) {
const currentPath = Path.resolve(__dirname, resourcePath);
const content = generateContent(context, currentPath);
saveFile(context, outResourcePath || resourcePath, content);
}
function randomString(len) {
const p = 'abcdefghijklmnopqrstuvwxyz0123456789';
/* eslint no-bitwise: [2, { allow: ["~"] }] */
return [...Array(len)].reduce(a => a + p[~~(Math.random() * p.length)], '');
}
function createDockerImageLayerResources(context) {
return new Promise((cb) => {
const {
imageIndexFilePath, outputFolder,
outputSubFolder, folderName,
} = context;
const imageIndexBuf = fs.readFileSync(imageIndexFilePath);
const tarballPath = `${outputFolder}/${outputSubFolder}/${folderName}/layer.tar`;
const tarball = fs.createWriteStream(tarballPath);
const pack = tar.pack({
dmode: parseInt(555, 8), // all dirs should be readable
fmode: parseInt(444, 8), // all files should be readable
});
const ext = Path.extname(imageIndexFilePath);
pack.entry({ name: `index${ext}` }, imageIndexBuf);
pack.pipe(tarball);
pack.finalize();
tarball.on('close', () => fs.stat(tarballPath, (err) => {
if (err) throw err;
const sha256tar = sha256File(tarballPath);
console.log('output: layer.tar');
cb({
...context,
sha256tar,
});
}));
});
}
function createDockerImageTopLevelResources(config) {
const {
imageName, outputFolder, imageIndexFilePath,
apiVersion = 1, packageVersion,
} = config;
const outputSubFolder = `.generated-${randomString(10)}`;
return new Promise((cb) => {
const context = {
imageName: `${imageName}-v${apiVersion}`,
repoTag: `${imageName}-v${apiVersion}:${packageVersion}`,
folderName: sha256(randomString(64)),
outputFolder,
imageIndexFilePath,
outputSubFolder,
packageVersion,
};
createResource(context, 'payload/repositories',
`${outputSubFolder}/repositories`);
const folderPath = `${outputSubFolder}/${context.folderName}`;
createResource(context, 'payload/folderName/json',
`${folderPath}/json`);
createResource(context, 'payload/folderName/VERSION',
`${folderPath}/VERSION`);
cb(context);
});
}
function createImageLayerResources(context) {
return new Promise((cb) => {
const resourcePath = 'payload/sha256ThisFile.json';
const currentPath = Path.resolve(__dirname, resourcePath);
const { outputSubFolder } = context;
const out = generateContent(context, currentPath);
const sha256Jsonfile = sha256(out);
const path = `${outputSubFolder}/${sha256Jsonfile}.json`;
saveFile(context, path, out);
cb({
...context,
sha256Jsonfile,
});
});
}
function createImageJson(context) {
const { outputSubFolder } = context;
createResource(context, 'payload/manifest.json',
`${outputSubFolder}/manifest.json`);
return context;
}
function createTar(context) {
return new Promise((cb) => {
const { outputFolder, outputSubFolder, imageName, packageVersion } = context;
const sourceFolder = `${outputFolder}/${outputSubFolder}`;
const tarball = `${outputFolder}/${imageName}-${packageVersion}.tar`;
tarFs.pack(sourceFolder, {
dmode: parseInt(555, 8), // all dirs should be readable
fmode: parseInt(444, 8), // all files should be readable
})
.pipe(fs.createWriteStream(tarball).on('close', () => fs.stat(tarball, (err) => {
if (err) throw err;
console.log(`output: ${tarball}`);
cb(context);
})));
});
}
function cleanUp(context) {
const { outputFolder, outputSubFolder } = context;
const sourceFolder = `${outputFolder}/${outputSubFolder}`;
return fse.remove(sourceFolder);
}
function validate(config) {
return new Promise((cb) => {
if (!config) throw new Error('Cannot find config file - default.yml');
const { imageName, outputFolder, imageIndexFilePath } = config;
if (!imageName) throw new Error('Must provide "imageName"');
if (!outputFolder) throw new Error('Must provide "outputFolder"');
if (!imageIndexFilePath) throw new Error('Must provide "imageIndexFilePath"');
try {
fs.statSync(imageIndexFilePath);
} catch (err) {
throw new Error(`Cannot find "${imageIndexFilePath}"`);
}
try {
const pjson = 'package.json';
fs.statSync(pjson);
const json = JSON.parse(fs.readFileSync(pjson));
if (!json.version) {
throw new Error('no version');
}
config.packageVersion = json.version;
} catch (err) {
throw new Error(`Cannot read version from 'package.json'`);
}
cb(config);
});
}
function createPackage(config) {
// {name}.tar
// untar
// - repositories
// - manifest.json
// - {file: sha256sum}.json
// - {folder: random-generated-id}
// - json
// - layer.tar
// - VERSION
validate(config.package)
.catch(e => console.log(chalk.red(e.message)))
.then(packageConfig => packageConfig && createDockerImageTopLevelResources(packageConfig)
.then(context => createDockerImageLayerResources(context))
.then(context => createImageLayerResources(context))
.then(context => createImageJson(context))
.then(context => createTar(context))
.then(context => cleanUp(context)));
// .then(packageConfig => )
// createDockerImageTopLevelResources(packageConfig)
// .then(context => createDockerImageLayerResources(context))
// .then(context => createImageLayerResources(context))
// .then(context => createImageJson(context))
// .then(context => createTar(context))
// .then(context => cleanUp(context));
}
createPackage(Config);
|
import { MatMenuModule } from '@angular/material/menu';
import { ForgotPassComponent } from './page/forgotPass/forgotPass.component';
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MatFormFieldModule} from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './page/login/login.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RegisterComponent } from './page/register/register.component';
import { AdvertsPageComponent } from './page/adverts/adverts.component';
import { RepHeaderComponent } from './component/Header/header.component';
import { MatIconModule } from '@angular/material/icon';
import { HomeComponent } from './page/home.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { RepSidenavComponent } from './component/Sidenav/sidenav.component';
import { MatSidenavModule } from '@angular/material/sidenav';
import { RepCardComponent } from './component/Card/card.component';
import { FavoritesPageComponent } from './page/favorites/favorites.component';
import { AnnouncePageComponent } from './page/announce/announce.component';
import { DescriptionPageComponent } from './page/description/description.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { requestInterceptor } from './interceptors/request.interceptor';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
// Pages
AppComponent,
HomeComponent,
LoginComponent,
RegisterComponent,
ForgotPassComponent,
AdvertsPageComponent,
FavoritesPageComponent,
AnnouncePageComponent,
DescriptionPageComponent,
// Components
RepHeaderComponent,
RepSidenavComponent,
RepCardComponent,
],
imports: [
AppRoutingModule,
BrowserModule,
CommonModule,
FontAwesomeModule,
HttpClientModule,
BrowserAnimationsModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
MatMenuModule,
MatSidenavModule,
],
bootstrap: [AppComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: requestInterceptor,
multi: true
}
]
})
export class AppModule { }
|
package com.wisdombud.alumni.manage.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Maps;
import com.wisdombud.alumni.common.DicCommonSrv;
import com.wisdombud.alumni.manage.CollgeManageSrv;
import com.wisdombud.alumni.pojo.dic.DicCollege;
import com.wisdombud.alumni.pojo.dic.DicDegree;
import com.wisdombud.alumni.pojo.dic.DicSpecialty;
import com.wisdombud.alumni.vo.ZTreeVo;
@Service
public class CollgeManageSrvSrvImpl implements CollgeManageSrv {
@Autowired
private DicCommonSrv srv;
private Map<Integer, String> degrees;
private Map<Integer, String> getDegreeMap(List<DicDegree> list){
Map<Integer, String> map=Maps.newHashMap();
for(DicDegree inst : list){
if(inst.getId()!=null&&!map.containsKey(inst.getId())){
map.put(inst.getId(), inst.getCnName());
}
}
return map;
}
@Override
public List<ZTreeVo> buildCollegeTree() {
List<DicDegree> dicDegreeList=srv.findAll(DicDegree.class);
degrees = this.getDegreeMap(dicDegreeList);
List<DicCollege> colleges =srv.findAll(DicCollege.class);
List<ZTreeVo> list = new ArrayList<>();
for (DicCollege v : colleges) {
ZTreeVo vo = new ZTreeVo();
vo.setId(v.getId());
vo.setpId(0);
vo.setRight(true);
vo.setParent(true);
vo.setOpen(false);
vo.setName(v.getCnName());
vo.setEnName(v.getEnName());
list.add(vo);
list.addAll(buildChildren(v.getId()));
}
return list;
}
private List<ZTreeVo> buildChildren(Integer collegeId) {
List<DicSpecialty> specialtys = srv.findAllCollegeSpecialty(collegeId);
List<ZTreeVo> list = new ArrayList<>();
for (DicSpecialty v : specialtys) {
ZTreeVo vo = new ZTreeVo();
vo.setId(v.getId());
vo.setpId(collegeId);
vo.setRight(true);
String degree = degrees.get(v.getDegreeId());
vo.setName(v.getCnName() + (StringUtils.isNotBlank(degree) ? ("(" + degree + ")") : ""));
list.add(vo);
}
return list;
}
}
|
namespace HenryMeds.DB;
/// <summary>
/// An appointment is one or more availabilities
/// that have been booked by a client with a specific provider.
/// </summary>
public class Appointment
{
/// <summary>
/// Unique identifier.
/// </summary>
public int Id { get; set; }
/// <summary>
/// A collection of one or more availabilities that have been booked.
/// Note: We'll probably stick with just one for now.
/// </summary>
public required ICollection<Availability> Availabilities { get; set; }
/// <summary>
/// The client that booked the appointment.
/// </summary>
public required Client Client { get; set; }
/// <summary>
/// The provider that the appointment is with.
/// </summary>
public required Provider Provider { get; set; }
/// <summary>
/// A confirmation status.
/// </summary>
public AppointmentStatus Status { get; set; }
/// <summary>
/// Created date.
/// </summary>
public DateTime Created { get; set; }
/// <summary>
/// Date the appointment request expires.
/// This will be used to filter out appointments that have been requested but not confirmed
/// and that are available to be booked by other clients.
/// </summary>
public DateTime RequestExpires { get; set; }
}
|
import { join } from 'path';
import { open } from 'fs/promises';
const moveRegex = /(R|U|D|L)\s(\d+)/;
type Point = {
x: number;
y: number;
};
const knotsTouching = (head: Point, tail: Point) =>
(head.x === tail.x && head.y === tail.y) ||
(tail.x === head.x - 1 && tail.y === head.y - 1) ||
(tail.x === head.x && tail.y === head.y - 1) ||
(tail.x === head.x + 1 && tail.y === head.y - 1) ||
(tail.x === head.x - 1 && tail.y === head.y) ||
(tail.x === head.x + 1 && tail.y === head.y) ||
(tail.x === head.x - 1 && tail.y === head.y + 1) ||
(tail.x === head.x && tail.y === head.y + 1) ||
(tail.x === head.x + 1 && tail.y === head.y + 1);
const moveKnot = (head: Point, tail: Point) => {
if (knotsTouching(head, tail)) {
return;
}
if (head.x !== tail.x) {
tail.x += head.x > tail.x ? 1 : -1;
}
if (head.y !== tail.y) {
tail.y += head.y > tail.y ? 1 : -1;
}
};
const calculateNumberOfPlacesTailVisits = async (knots: number) => {
const file = await open(join('9', 'input.txt'));
const visitedPoints: Point[] = [{ x: 0, y: 0 }];
const currentPoints = [...Array(knots).keys()].map<Point>(() => ({
x: 0,
y: 0,
}));
const tail = currentPoints[knots - 1];
for await (const line of file.readLines()) {
const lineMatch = line.match(moveRegex)!;
const direction = lineMatch[1];
const units = parseInt(lineMatch[2], 10);
const doMoves = (handleHead: () => void) => {
for (let i = 0; i < units; ++i) {
handleHead();
for (let i = 0; i < currentPoints.length; ++i) {
if (i < currentPoints.length - 1) {
moveKnot(currentPoints[i], currentPoints[i + 1]);
}
}
if (
!visitedPoints.some(
(point) => point.x === tail.x && point.y === tail.y
)
) {
visitedPoints.push({ ...tail });
}
}
};
switch (direction) {
case 'D':
doMoves(() => {
--currentPoints[0].y;
});
break;
case 'U':
doMoves(() => {
++currentPoints[0].y;
});
break;
case 'R':
doMoves(() => {
++currentPoints[0].x;
});
break;
case 'L':
doMoves(() => {
--currentPoints[0].x;
});
break;
}
}
return visitedPoints.length;
};
const solution = async (knots: number) => {
console.log(
`Finding number of points tail of rope with ${knots} knots visits`
);
console.log(
`Rope visits ${await calculateNumberOfPlacesTailVisits(knots)} points`
);
};
export const solution1 = async () => await solution(2);
export const solution2 = async () => await solution(10);
|
// Register UI. Each input field must be filled to create a user.
<template>
<div class="wrapper">
<img src="../../src/assets/smallLogo.png" alt="" width="50" height="50">
<div class="text-center mt-4 name"> IntegrationWorks </div>
<form class="p-3 mt-3" @submit.prevent="register">
<div class="row">
<div class="form-field d-flex align-items-center col-md-6 mb-4">
<span class="far fa-user"></span>
<input type="text" name="fName" id="fName" placeholder="First Name" v-model="fName">
</div>
<div class="form-field d-flex align-items-center col-md-6 mb-4">
<span class="far fa-user"></span>
<input type="text" name="lName" id="lName" placeholder="Last Name" v-model="lName">
</div>
</div>
<div class="form-field d-flex align-items-center">
<span class="far fa-user"></span>
<input type="text" name="jobName" id="jobName" placeholder="Job Title" v-model="jobName">
</div>
<div class="form-field d-flex align-items-center">
<span class="far fa-user"></span>
<input type="text" name="email" id="email" placeholder="Email" v-model="enteredEmail">
</div>
<div class="form-field d-flex align-items-center">
<span class="fas fa-key"></span>
<input type="password" name="password" id="pwd" placeholder="Password" v-model="enteredPassword">
</div>
<div class="form-field d-flex align-items-center">
<span class="fas fa-key"></span>
<input type="password" name="password" id="pwd" placeholder="Confirm Password" v-model="enteredPassword">
</div>
<div class="row">
<div class="d-flex align-items-center col-md-6 mb-4"><button class="btn mt-3">Back</button></div>
<div class="d-flex align-items-center col-md-6 mb-4"><button class="btn mt-3" v-on:click="post">Sign up</button></div>
</div>
</form>
<div class="text-center fs-6"> <a href="#">Forget password?</a> or <router-link to="/register">Register</router-link></div>
</div>
</template>
// When a user fills up all the fields and click sign up, the request data in json format will be passed to the lambda function.
// There will be a message when creation is successful.
<script>
import {useRouter} from 'vue-router'
import {ref, provide} from 'vue'
//import addEmployee from '../api/http'
export default {
setup(){
const router = useRouter();
const fName = ref("");
const lName = ref("");
const jobName = ref("");
const enteredEmail = ref("");
const enteredPassword = ref("");
provide('regEmail', enteredEmail)
return{
router,
enteredEmail,
enteredPassword,
fName,
lName,
jobName
}
},
methods:{
post() {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
firstName: this.fName,
lastName: this.lName,
jobTitle: this.jobName,
email: this.enteredEmail
})
};
var url = "https://ssp8p1cf45.execute-api.ap-southeast-2.amazonaws.com/Prod/api/v1/skills/employees/";
fetch(url, requestOptions)
.then(response => response.json())
.then(data => ( console.log(data.id)));
alert( this.fName + " added")
},
},
// provide:{
// username: this.enteredEmail,
// userpassword: this.enteredEmail,
// }
}
</script>
// IW brand font and colors are used
<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Open Sans', sans-serif
}
body {
background: #F8F5Ec
}
.wrapper {
max-width: 400px;
min-height: 500px;
margin: auto;
padding: 40px 30px 30px 30px;
background-color: #ecf0f3;
border-radius: 15px;
box-shadow: 13px 13px 20px #cbced1, -13px -13px 20px #fff
}
.logo {
width: 80px;
margin: auto
}
.logo img {
width: 100%;
height: 80px;
object-fit: cover;
border-radius: 50%;
box-shadow: 0px 0px 3px #5f5f5f, 0px 0px 0px 5px #ecf0f3, 8px 8px 15px #a7aaa7, -8px -8px 15px #fff
}
.wrapper .name {
font-weight: 600;
font-size: 1.4rem;
letter-spacing: 1.3px;
padding-left: 10px;
color: #555
}
.wrapper .form-field input {
width: 100%;
display: block;
border: none;
outline: none;
background: none;
font-size: 1rem;
color: #666;
padding: 10px 15px 10px 10px
}
.wrapper .form-field {
padding-left: 10px;
margin-bottom: 20px;
border-radius: 20px;
border: 1px solid #adadad;
/* box-shadow: inset 8px 8px 8px #cbced1, inset -8px -8px 8px #fff */
}
.wrapper .form-field .fas {
color: #555
}
.wrapper .btn {
box-shadow: none;
width: 97%;
height: 40px;
background-color: #01131b;
color: #fff;
border-radius: 25px;
box-shadow: 3px 3px 3px #b1b1b1, -3px -3px 3px #fff;
letter-spacing: 1.3px
}
.wrapper .btn:hover {
background-color: #B92222
}
.wrapper a {
text-decoration: none;
font-size: 0.8rem;
color: #B92222
}
.wrapper a:hover {
color: #01131b
}
@media(max-width: 380px) {
.wrapper {
margin: 30px 20px;
padding: 40px 15px 15px 15px
}
}
.btn-confirm {
width:150px;
height:30px;
font-size: 11pt;
}
.txt {
width: 300px;
height: 40px;
color: black;
border-block-end-color: black;
border-block-start-color: black;
border-left-color: black;
border-right-color: black;
padding-left: 10px;
font-size:10pt;
}
</style>
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<!-- Bootstrap CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<title>註冊頁面</title>
<style>
body {
background-color: rgb(255, 252, 233) !important;
background-attachment: fixed;
margin: 0;
padding: 0;
background-image: url("../img/web/jojo_bird.png");
background-position: right bottom;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 20%;
}
.centered-card {
display: flex;
/* justify-content: center; */
align-items: center;
min-height: 100vh;
/* 100% viewport height */
}
#Register #checkEyeforModel {
font-size: 22px;
position: absolute;
top: 56%;
cursor: pointer;
right: 45px;
/* 調整眼睛圖示與右側的距離 */
}
</style>
</head>
<body>
<div th:replace="~{layout/navbar_onlyLogo}"></div>
<section class="centered-card" id="Register">
<div class="container h-100">
<div class="row justify-content-sm-center h-100">
<div class="col-xxl-4 col-xl- col-lg-5 col-md-7 col-sm-9">
<div class="card shadow rounded-5">
<div class="card-body p-4">
<h2 class="card-title text-center fw-bold mb-4">註冊帳號</h2>
<form @submit.prevent="registerClick" class="px-3">
<!-- email -->
<div class="md-form mb-2">
<div class="input-group borderless">
<span class="input-group-text">
<i class="bi bi-envelope"></i>
</span>
<input v-model="email" type="text" class="form-control form-control-lg"
:class="{'is-invalid': emailCheckno},{'invalid': emailCheckok}"
name="username" placeholder="電子信箱" autofocus />
<button class="btn btn-warning shadow-sm"
@click="sendEmailVolidCode">寄送驗證碼</button>
</div>
<div class="mt-2">
<span v-text="emailMessage"
:class="[{'text-danger': emailCheckno},{'text-success': emailCheckok},'mt-2']">
</span>
</div>
</div>
<!-- emailvolidcode -->
<div class="md-form mb-2">
<div class="input-group borderless">
<span class="input-group-text">
<i class="bi bi-pencil-square"></i>
</span>
<input v-model="voildcode" type="text" class="form-control form-control-lg"
placeholder="驗證碼" />
</div>
<div class="mt-2">
<span v-text="emailvolidcodemsg"
:class="[{'text-danger': emailvolidcodeno},{'text-success': emailvolidcodeok},{'text-warning': emailvolidloading}]"></span>
<div v-if="emailvolidloading"
class="spinner-border spinner-border-sm text-warning mx-2 " role="status">
<span class="visually-hidden"> Loading...</span>
</div>
</div>
</div>
<!-- username -->
<div class="md-form mb-2">
<div class="input-group borderless">
<span class="input-group-text">
<i class="bi bi-people-fill"></i>
</span>
<input v-model="username" type="text"
class="form-control form-control-lg validate" placeholder="姓名" autofocus />
</div>
<div class="mt-2">
<span v-text="usernameMessage"
:class="[{'text-danger': usernameCheckno},{'text-success': usernameCheckok}]">
</span>
</div>
</div>
<!-- TellPhone -->
<div class="md-form mb-2">
<div class="input-group borderless">
<span class="input-group-text">
<i class="bi bi-telephone-fill"></i>
</span>
<select v-model="selected" class="form-select form-select-lg validate">
<option v-for="pcode in phonecodes" :value="pcode.value">
{{pcode.text}}
</option>
</select>
<input v-model="phonenumber" type="tel" class="form-control form-control-lg"
:class="{'is-invalid': phonenumberCheckno},{'invalid': phonenumberCheckok}"
placeholder="手機" />
</div>
<div class="mt-2">
<span v-text="phonenumberMessage"
:class="[{'text-danger': phonenumberCheckno},{'text-success': phonenumberCheckok},'mt-2']">
</span>
</div>
</div>
<!-- password -->
<div class="md-form mb-2">
<div class="input-group borderless">
<span class="input-group-text">
<i class="bi bi-lock-fill"></i>
</span>
<input v-model="password" :type="isActive ? 'password' : 'text'"
class="form-control form-control-lg"
:class="{'is-invalid': passwordCheckno},{'invalid': passwordCheckok}"
placeholder="密碼" />
</div>
<i id="checkEyeforModel" :class="isActive ? 'bi bi-eye-slash' : 'bi bi-eye'"
@click="isActive=!isActive"></i>
<div class="mt-2">
<span v-text="passwordMessage"
:class="[{'text-danger': passwordCheckno},{'text-success': passwordCheckok}]" />
</div>
</div>
<div class="text-center d-grid gap-2">
<button class="btn btn-block mt-3 btn-warning rounded-pill">註冊</button>
</div>
<div class="text-center mt-4">
已經是Jo寶了,可以前往 <a th:href="@{/login}">登入</a>
<!-- <a href="/register">註冊</a> -->
</div>
</form>
<div class="text-center">
<div class="d-flex" style="margin-top: 1em;margin-bottom: 1em">
<hr class="my-auto flex-grow-1">
<div class="px-4">使用其他帳號登入</div>
<hr class="my-auto flex-grow-1">
</div>
<a href="/oauth2/authorization/google" style="background-color: transparent">
<button class="gsi-material-button">
<div class="gsi-material-button-state"></div>
<div class="gsi-material-button-content-wrapper">
<div class="gsi-material-button-icon">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 48 48" xmlns:xlink="http://www.w3.org/1999/xlink"
style="display: block">
<path fill="#EA4335"
d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z">
</path>
<path fill="#4285F4"
d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z">
</path>
<path fill="#FBBC05"
d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z">
</path>
<path fill="#34A853"
d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z">
</path>
<path fill="none" d="M0 0h48v48H0z"></path>
</svg>
</div>
<span class="gsi-material-button-contents">使用 Google 帳戶註冊</span>
<span style="display: none">Sign in with Google</span>
</div>
</button>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- 引入 Vue.js 和 Axios -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.21/vue.global.prod.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.8/axios.min.js"></script>
<!-- 引入 Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script type="module">
Vue.createApp({
data() {
return {
selected: "+886",
phonecodes: [
{ value: "+886", text: "台灣 +886" },
{ value: "+86", text: "中國 +86" },
{ value: "+852", text: "香港 +852" },
{ value: "+60", text: "馬來西亞 +60" },
{ value: "+853", text: "澳門 +853" },
{ value: "+81", text: "日本 +81" },
{ value: "+82", text: "韓國 +82" },
{ value: "+63", text: "菲律賓 +63" },
{ value: "+65", text: "新加坡 +65" },
{ value: "+1", text: "美國 +1" },
{ value: "+0", text: "其他 +0" }
],
email: "",
phonenumber: "",
username: "",
password: "",
errormsg: false,
emailCheckok: false,
emailCheckno: false,
emailMessage: "",
emailimg: "",
usernameCheckok: false,
usernameCheckno: false,
usernameMessage: "",
usernameimg: "",
emailCheckok: false,
emailCheckno: false,
emailMessage: "",
phonenumberemailimg: "",
phonenumberCheckok: false,
phonenumberCheckno: false,
phonenumberMessage: "",
img: "",
passwordCheckok: false,
passwordCheckno: false,
passwordMessage: "",
passwordimg: "",
acceptIcon: "/img/icon/accept.png",
cancelIcon: "/img/icon/cancel.png",
emailvolidcodeok: false,
emailvolidcodeno: false,
emailvolidcodemsg: "",
emailvolidloading: false,
voildcode: "",
isActive: true,
}
},
methods: {
registerClick() {
if (!this.emailCheckok || !this.usernameCheckok || !this.passwordCheckok || !this.phonenumberCheckok) {
//console.log("阻止提交表單");
return; // 阻止提交表單
}
let uTel = `${this.selected}-${his.phonenumber}`;
const raw = JSON.stringify({
uAccountEmail: this.email,
uTel: uTel,
uName: this.username,
uPwd: this.password,
uidCode: this.voildcode,
});
axios.post("/register", raw, {
headers: {
"Content-Type": "application/json",
},
})
.then(rs => {
// //console.log(rs.data)
//console.log("註冊成功");
$("#RegisterModal").modal("hide");
$("#successRegisterModal").modal("show");
})
.catch(error => {
this.errormsg = true;
console.error(error);
// this.error = true;
});
},
sendEmailVolidCode() {
if (!this.emailCheckok || !this.email.trim()) {
//console.log("阻止提交表單,驗證碼");
return; // 阻止提交表單
}
const formdata = new FormData();
formdata.append("email", this.email);
axios.post("/api/checkEmail", formdata)
.then((rs) => {
this.emailvolidcodemsg = "驗證碼正在寄送,請稍待片刻";
this.emailvolidloading = true;
axios.post("/api/sentEmailVolidCode", formdata)
.then(rs => {
let volidCount = rs.data.volidCount
if (volidCount < 3) {
this.emailvolidcodemsg = `驗證碼已發送至您的信箱,請查收。您已進行 ${volidCount} 次驗證。` + "請注意,最多發送 3 次。";
this.emailvolidcodeok = true;
this.emailvolidcodeno = false;
this.emailvolidloading = false;
} else {
this.emailvolidcodemsg = '注意這是最後一次寄送驗證,之後請在5分鐘後再試~。';
this.emailvolidcodeok = true;
this.emailvolidcodeno = false;
this.emailvolidloading = false;
}
})
.catch(error => {
console.error(error);
this.emailvolidcodemsg = "超過驗證次數,請5分鐘後再試";
this.emailvolidcodeok = false;
this.emailvolidcodeno = true;
this.emailvolidloading = false;
});
})
.catch((error) => {
this.emailvolidcodemsg = "已存在信箱,請重新輸入";
this.emailvolidcodeok = false;
this.emailvolidcodeno = true;
this.emailvolidloading = false;
console.error("Error:", error);
});
}
},
watch: {
email(newValue, oldValue) {
let re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
let isValidEmail = re.test(newValue);
if (!newValue.trim()) {
this.emailCheckno = true;
this.emailCheckok = false;
this.emailMessage = "必填";
this.emailimg = cancelIcon;
} else if (isValidEmail) {
this.emailCheckok = true;
this.emailCheckno = false;
this.emailMessage = "格式符合";
this.emailimg = acceptIcon;
} else {
this.emailCheckok = false;
this.emailCheckno = true;
this.emailMessage = "信箱格式錯誤";
this.emailimg = cancelIcon;
}
},
password(newValue, oldValue) {
let re = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[#?!@$%^&*-_])[a-zA-Z0-9#?!@$%^&*-_]{7,20}$/;
let isValidPwd = re.test(newValue);
if (!newValue.trim()) {
this.passwordCheckno = true;
this.passwordCheckok = false;
this.passwordMessage = "必填";
this.passwordimg = cancelIcon;
} else if (isValidPwd) {
this.passwordCheckok = true;
this.passwordCheckno = false;
this.passwordMessage = "格式符合";
this.passwordimg = acceptIcon;
} else {
this.passwordCheckok = false;
this.passwordCheckno = true;
this.passwordMessage = "密碼長度7~20字,含英文字母和數字,不可空格,支援特殊字元 #?!@$%^&*-_";
this.passwordimg = cancelIcon;
}
},
phonenumber(newValue, oldValue) {
let re = /^\d{7,20}$/;
let isValidphone = re.test(newValue);
if (!newValue.trim()) {
this.phonenumberCheckok = false;
this.phonenumberCheckno = true;
this.phonenumberMessage = "必填";
this.phonenumberimg = cancelIcon;
} else if (isValidphone) {
this.phonenumberCheckok = true;
this.phonenumberCheckno = false;
this.phonenumberMessage = "格式符合";
this.phonenumberimg = acceptIcon;
} else {
this.phonenumberCheckok = false;
this.phonenumberCheckno = true;
this.phonenumberMessage = "電話號碼為7~20字的數字";
this.phonenumberimg = cancelIcon;
}
},
username(newValue, oldValue) {
if (!newValue.trim()) {
this.usernameCheckok = false;
this.usernameCheckno = true;
this.usernameMessage = "必填";
this.usernameimg = cancelIcon;
} else {
this.usernameCheckok = true;
this.usernameCheckno = false;
this.usernameMessage = "格式符合";
this.usernameimg = acceptIcon;
}
}
}
}).mount("#Register");
</script>
<script>
function register() {
let errorMessage = document.getElementById("error-message");
errorMessage.style.display = "none";
errorMessage.innerText = "";
let uAccountEmail = document.getElementById("uAccountEmail").value;
let uPwd = document.getElementById("uPwd").value;
let uName = document.getElementById("uName").value;
let countryPhone = document.getElementById("countryPhone").value;
let phoneNumber = document.getElementById("phoneNumber").value;
if (!uAccountEmail || !uPwd || !uName || !phoneNumber) {
errorMessage.style.display = "block";
errorMessage.innerText = "請輸入完整資訊";
} else {
let uTel = countryPhone + phoneNumber;
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
const raw = JSON.stringify({
"uAccountEmail": uAccountEmail,
"uPwd": uPwd,
"uTel": uTel,
"uName": uName
});
const requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow"
};
fetch("http://localhost:8081/register", requestOptions)
.then((response) => {
if (response.ok) {
//console.log("註冊成功");
// 清空輸入框的內容
let successMessageDiv = document.getElementById("error-message");
successMessageDiv.classList.remove("alert-danger"); // 移除錯誤樣式
successMessageDiv.classList.add("alert-success"); // 添加成功樣式
successMessageDiv.style.display = "block";
successMessageDiv.innerHTML = "帳號註冊成功,請前往至登入頁面。";
document.getElementById("uAccountEmail").value = "";
document.getElementById("uPwd").value = "";
document.getElementById("uName").value = "";
document.getElementById("phoneNumber").value = "";
} else {
// 如果註冊失敗,顯示錯誤信息
return response.text().then(errorMessage => {
console.error(errorMessage);
let errorMessageDiv = document.getElementById("error-message");
errorMessageDiv.style.display = "block";
errorMessageDiv.innerText = errorMessage;
// 清空輸入框的內容
document.getElementById("uPwd").value = "";
document.getElementById("uAccountEmail").value = "";
document.getElementById("uName").value = "";
document.getElementById("phoneNumber").value = "";
});
}
})
.catch((error) => console.error(error));
}
}
</script>
</body>
</html>
|
import { CanActivate, ExecutionContext, Injectable, NotFoundException, UnauthorizedException } from "@nestjs/common";
import { Observable } from "rxjs";
import { Friendship } from "src/friendships/entities/friendship.entity";
import { FriendshipsService } from "src/friendships/friendships.service";
@Injectable()
export class UserInFriendshipGuard implements CanActivate {
constructor(
private readonly friendshipService: FriendshipsService
) {}
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
const user = request.user;
const params = request.params;
if (user && user.id && params && params.id) {
return this.checkIfUserInFriendship(user.id, params.id);
}
return false;
}
private async checkIfUserInFriendship(userId: number, friendshipId: number): Promise<boolean> {
const friendship: Friendship = await this.friendshipService.findOneById(friendshipId);
if (!friendship)
throw new NotFoundException();
if (userId == friendship.user1Id || userId == friendship.user2Id)
return true;
throw new UnauthorizedException('User must be member of friendship');
}
}
|
# QUESTION 107:- Average of Levels in Binary Tree
# DESCRIPTION:- Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.
# EXAMPLE1:
Input: root = [3,9,20,null,null,15,7]
Output: [3.00000,14.50000,11.00000]
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
Hence return [3, 14.5, 11].
# Example 2:
Input: root = [3,9,20,15,7]
Output: [3.00000,14.50000,11.00000]
# SOLUTION 107:-
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double>ans;
queue<TreeNode*> q;
q.push(root);
if(root == NULL){
return ans;
}
while(!q.empty()){
int s = q.size();
long long sum = 0;
for(int i = 0; i < s; i++){
TreeNode* front = q.front();
int value = front->val;
sum += value;
q.pop();
if(front -> left) q.push(front->left);
if(front -> right) q.push(front -> right);
}
double avg = (double)sum / s;
ans.push_back(avg);
}
return ans;
}
};
# QUESTION 108:- Binary Tree Level Order Traversal
# DESCRIPTION:-Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
# EXAMPLE1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
# Example 2:
Input: root = [1]
Output: [[1]]
# SOLUTION 108:-
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
vector<vector<int> >mainAns;
if(root == NULL){
return mainAns;
}
while(!q.empty()){
int s = q.size();
vector<int> ans;
for(int i = 0; i < s; i++){
TreeNode* front = q.front();
ans.push_back(front->val);
q.pop();
if(front -> left) q.push(front -> left);
if(front -> right) q.push(front -> right);
}
mainAns.push_back(ans);
}
return mainAns;
}
};
|
// Copied from commitStatusHelper.ts in the frontend repository
import { differenceInHours, isAfter } from 'date-fns'
import {
Commit,
CommitWithAnalysis,
CoverageAnalysis,
CoveragePullRequestResponse,
PullRequestCoverage,
PullRequestWithAnalysis,
QualityAnalysis,
} from '../api/client'
export interface StatusProps {
value: 'loading' | 'passed' | 'failed' | 'noInformation'
message: string
details?: string
// VSCODE Custom Props
icon?: string
colorId?: string
}
/** COVERAGE */
const REPORTS_WAIT_TIME = 3 // hours
const CoverageStatus: Record<string, StatusProps> = {
waiting: { value: 'loading', message: 'Pending...', icon: 'loading~spin' },
passed: { value: 'passed', message: 'Up to coverage standards.', icon: 'pass', colorId: 'testing.iconPassed' },
failed: { value: 'failed', message: 'Not up to coverage standards.', icon: 'error', colorId: 'testing.iconFailed' },
noCoverage: { value: 'noInformation', message: 'No information.', icon: 'circle-slash' },
}
const getCoverageStatus = (
isWaitingForAnalysis: boolean,
lastUpdated: string,
coverage?: PullRequestCoverage | CoverageAnalysis
) => {
const isRecentlyUpdated = differenceInHours(new Date(), new Date(lastUpdated)) <= REPORTS_WAIT_TIME
const status = isWaitingForAnalysis
? isRecentlyUpdated
? 'waiting'
: 'noCoverage'
: coverage?.isUpToStandards ||
coverage?.resultReasons?.length === 0 ||
!coverage?.resultReasons?.some((reason) => !reason.isUpToStandards)
? 'passed'
: 'failed'
return status
}
export const isCommitBeingAnalysed = (commit: Commit) =>
!!commit?.startedAnalysis &&
(!commit.endedAnalysis || isAfter(new Date(commit.startedAnalysis), new Date(commit.endedAnalysis)))
export const getCoverageCommitStatus = (data: CommitWithAnalysis) => {
const isWaitingForAnalysis = !data.commit.endedAnalysis || !data.coverage?.totalCoveragePercentage
const status = getCoverageStatus(isWaitingForAnalysis, data.commit.commitTimestamp, data.coverage)
return CoverageStatus[status]
}
const isWaitingForCoverageResults = (data: PullRequestWithAnalysis) =>
data.isAnalysing ||
(data.coverage?.deltaCoverage === undefined &&
(data.coverage?.diffCoverage === undefined ||
(data.coverage?.diffCoverage?.value === undefined &&
data.coverage?.diffCoverage?.cause === 'MissingRequirements')))
export const getCoveragePRStatus = (data: PullRequestWithAnalysis, reports?: CoveragePullRequestResponse) => {
const status = getCoverageStatus(isWaitingForCoverageResults(data), data.pullRequest.updated, data.coverage)
const result = CoverageStatus[status]
if (reports?.data) {
// with extra information about the reports, decorate the status with more information
const { headCommit, commonAncestorCommit } = reports.data
if (status === 'waiting') {
if (headCommit.reports.length === 0) return { ...result, details: 'Waiting for coverage reports...' }
if (headCommit.reports.length > 0 && commonAncestorCommit.reports.length > 0)
return { ...result, details: 'Processing coverage reports...' }
} else if (status === 'noCoverage') {
if (headCommit.reports.length === 0 || commonAncestorCommit.reports.length === 0)
return { ...result, details: 'Missing coverage reports' }
else return { ...result, details: "Couldn't process coverage" }
}
}
return result
}
/** QUALITY */
const QualityStatus: Record<string, StatusProps> = {
waiting: { value: 'loading', message: 'Analysing...', icon: 'loading~spin' },
passed: { value: 'passed', message: 'Up to quality standards.', icon: 'pass', colorId: 'testing.iconPassed' },
failed: { value: 'failed', message: 'Not up to quality standards.', icon: 'error', colorId: 'testing.iconFailed' },
noInfo: { value: 'noInformation', message: 'No information.', icon: 'circle-slash' },
}
const getQualityStatusValue = (isWaitingForAnalysis: boolean, isAnalyzable: boolean, quality?: QualityAnalysis) => {
const status = isWaitingForAnalysis
? !isAnalyzable
? 'noInfo'
: 'waiting'
: quality?.isUpToStandards === undefined || !isAnalyzable
? 'noInfo'
: quality.isUpToStandards ||
quality.resultReasons?.length === 0 ||
!quality.resultReasons?.some((reason) => !reason.isUpToStandards)
? 'passed'
: 'failed'
return status
}
const getQualityCommonStatus = (
data: CommitWithAnalysis | PullRequestWithAnalysis,
isWaitingForAnalysis: boolean,
isWaitingForCoverage: boolean,
isAnalyzable: boolean,
lastUpdated: string,
expectCoverage: boolean
) => {
const qualityStatus = getQualityStatusValue(isWaitingForAnalysis, isAnalyzable, data.quality)
const coverageStatus = expectCoverage
? getCoverageStatus(isWaitingForCoverage, lastUpdated, data.coverage)
: undefined
const useCoverageStatus = expectCoverage && qualityStatus !== 'failed' && coverageStatus === 'failed'
const status = useCoverageStatus ? coverageStatus : qualityStatus
const result = {
...(useCoverageStatus ? CoverageStatus[status] : QualityStatus[status]),
quality: QualityStatus[qualityStatus],
...(coverageStatus ? { coverage: CoverageStatus[coverageStatus] } : undefined),
}
if (result.coverage && qualityStatus === 'passed' && coverageStatus !== 'passed') {
switch (coverageStatus) {
case 'waiting':
return { ...result, details: 'Waiting for coverage reports...' }
case 'noCoverage':
return { ...result, details: 'Missing coverage reports' }
}
}
if (status === 'noInfo' && data.meta.reason) {
return { ...result, details: data.meta.reason }
}
return result
}
export const getQualityStatus = (data: CommitWithAnalysis | PullRequestWithAnalysis, expectCoverage: boolean) =>
'pullRequest' in data ? getQualityPRStatus(data, expectCoverage) : getQualityCommitStatus(data, expectCoverage)
export type QualityStatusResponse = ReturnType<typeof getQualityStatus>
export const getQualityCommitStatus = (data: CommitWithAnalysis, expectCoverage: boolean) =>
getQualityCommonStatus(
data,
isCommitBeingAnalysed(data.commit),
!data.coverage?.totalCoveragePercentage,
data.meta.analyzable && !!data.commit.endedAnalysis && !!data.commit.startedAnalysis,
data.commit.commitTimestamp,
expectCoverage
)
export const getQualityPRStatus = (data: PullRequestWithAnalysis, expectCoverage: boolean) =>
getQualityCommonStatus(
data,
data.isAnalysing,
isWaitingForCoverageResults(data),
data.meta.analyzable,
data.pullRequest.updated,
expectCoverage
)
|
//
// RealmManager.swift
// SpaceX
//
// Created by Karim Sakr on 03/11/2023.
//
import Foundation
import RealmSwift
class RealmManager: ObservableObject, RealmManagerProtocol {
static let shared = RealmManager()
private var realm: Realm?
var launches = [Launch]()
private init() {
openRealm()
getLaunches()
}
//MARK: - Save
func saveLaunches(of allSuccessfulLaunches: [Launch]) {
guard let realm = realm else {
return
}
do {
try realm.write {
let oldLaunches = realm.objects(Launch.self)
if oldLaunches.isEmpty {
realm.add(allSuccessfulLaunches)
} else {
for newLaunch in allSuccessfulLaunches {
// replace items
if let existingLaunch = oldLaunches.first(where: { $0.id == newLaunch.id }) {
existingLaunch.rocket = newLaunch.rocket
existingLaunch.links = newLaunch.links
existingLaunch.success = newLaunch.success
existingLaunch.details = newLaunch.details
existingLaunch.flightNumber = newLaunch.flightNumber
existingLaunch.name = newLaunch.name
existingLaunch.dateUtc = newLaunch.dateUtc
existingLaunch.dateUnix = newLaunch.dateUnix
existingLaunch.dateLocal = newLaunch.dateLocal
existingLaunch.upcoming = newLaunch.upcoming
}
}
}
}
getLaunches()
} catch {
print(error.localizedDescription)
}
}
func openRealm() {
do {
let config = Realm.Configuration()
Realm.Configuration.defaultConfiguration = config
realm = try Realm()
} catch {
print(error.localizedDescription)
}
}
//MARK: - Get
func getLaunches() {
guard let realm = realm else {
return
}
let allLaunches = realm.objects(Launch.self)
launches = []
for launch in allLaunches {
launches.append(launch)
}
}
}
|
import React from "react";
import { API_BASE_URL } from "../config/variables";
import secureImage from "./images/secure.svg";
import { faEllipsisV } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import FadeIn from 'react-fade-in';
import LoginView from "./LoginView";
import RegisterView from "./RegisterView";
import Table from "../components/Table";
export default class ProfileView extends React.Component {
state = {
isLogin: false,
isRegister: false,
errMsg: "",
};
constructor(props) {
super(props);
}
_fetchLogout = async () => {
const bearer = "Bearer " + localStorage.getItem("jwt");
await fetch(API_BASE_URL + "/customer/logout", {
method: "POST",
body: JSON.stringify({
userID: this.props.user.id,
}),
headers: {
"Content-Type": "application/json",
Authorization: bearer,
},
})
.then((response) => {
return response.json();
})
.then((responseData) => {
if (responseData.errorMsg) {
this._updateErrMsg(responseData.errorMsg);
} else {
localStorage.setItem("jwt", null);
this.props.updateUser(null);
}
});
};
// _fetchDeleteAccount = async() =>{
// const bearer = "Bearer " + localStorage.getItem("jwt");
// await fetch(API_BASE_URL + "/customer/delete-account", {
// method: "POST",
// body: JSON.stringify({
// userID: this.props.user.id,
// }),
// headers: {
// "Content-Type": "application/json",
// Authorization: bearer,
// },
// })
// .then((response) => {
// return response.json();
// })
// .then((responseData) => {
// if (responseData.errorMsg) {
// this._updateErrMsg(responseData.errorMsg);
// } else {
// localStorage.setItem("jwt", null);
// this.props.updateUser(null);
// }
// });
// }
_selectRegister = () => {
let newState = this.state;
newState.isRegister = true;
newState.isLogin = false;
this.setState(newState);
};
_selectLogin = () => {
let newState = this.state;
newState.isRegister = false;
newState.isLogin = true;
this.setState(newState);
};
_selectProfile = () => {
let newState = this.state;
newState.isRegister = false;
newState.isLogin = false;
this.setState(newState);
};
_updateErrMsg = (msg) => {
if (typeof msg == "object") {
msg = JSON.stringify(msg);
}
let newState = this.state;
newState.errMsg = msg;
this.setState(newState);
};
_renderOptions = () => {
return (
<FadeIn>
<div className="col-lg-12 card p-card" style={{ minHeight: "30em" }}>
<div className="row">
<div className="col-lg-6 h-100">
<img src={secureImage} style={{ width: "100%" }} />
</div>
<div className="col-lg-6 h-100 text-center">
<div className="col-lg-12">
<h4 style={{ marginBottom: "150px" }}>
Please select one of the following:
</h4>
</div>
<div className="col-lg-12 d-inline" style={{ marginTop: "30%" }}>
<button
onClick={this._selectLogin}
className="btn btn-primary btn-lg"
>
Login
</button>
<p
style={{
display: "inline",
marginRight: "30px",
marginLeft: "30px",
}}
>
Or
</p>
<button
onClick={this._selectRegister}
className="btn btn-primary btn-lg"
>
Register
</button>
</div>
</div>
</div>
</div>
</FadeIn>
);
};
_renderLogin = () => {
return (
<LoginView
toggleBack={this._selectProfile}
updateErrMsg={this._updateErrMsg}
updateUser={this.props.updateUser}
/>
);
};
_renderRegister = () => {
return (
<RegisterView
toggleBack={this._selectProfile}
updateErrMsg={this._updateErrMsg}
updateUser={this.props.updateUser}
/>
);
};
_calculateInfo = () =>{
var total = 0;
var itemsLen = 0;
var orderLength = this.props.user.orders.length;
for(var i=0;i<this.props.user.orders.length;++i){
total = total + this.props.user.orders[i].totalPrice;
for(var ix=0;ix<this.props.user.orders[i].items.length;++ix){
itemsLen = itemsLen + this.props.user.orders[i].items[ix].quantity;
}
}
var obj = {
total:total,
itemsLen:itemsLen,
orderLength:orderLength
}
return obj;
}
_renderProfile = () => {
var infoObj = this._calculateInfo();
var date = new Date(this.props.user.dateCreated);
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : "0" + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : "0" + day;
var formattedDate = month + "/" + day + "/" + year;
return (
<FadeIn>
<div className="container">
<div className="row">
<div className="col-md-4">
<div className="card p-card" style={{maxHeight:"100%" }}>
<div className="row">
<div className="col-lg-8">
<h6 style={{ fontWeight: "bold" }}>My Profile:</h6>
</div>
<div className="col-lg-4">
<FontAwesomeIcon
className="dropdown-toggle"
id="dropdownMenuButton"
data-toggle="dropdown"
icon={faEllipsisV}
style={{
float: "right",
fontSize: "20px",
cursor: "pointer",
}}
/>
<div
class="dropdown-menu"
style={{ minWidth: "6rem" }}
aria-labelledby="dropdownMenuButton"
>
<p
onClick={this._fetchLogout}
class="dropdown-item"
style={{
color: "black",
marginBottom: 0,
cursor: "pointer",
}}
>
Logout
</p>
{/* <div class="dropdown-divider"></div>
<p
onClick={this._fetchDeleteAccount}
class="dropdown-item"
style={{
color: "#E25950",
marginBottom: 0,
cursor: "pointer",
}}
>
Delete Account
</p> */}
</div>
</div>
</div>
<div className="col-lg-12 text-center">
<img
src="https://images.unsplash.com/photo-1537815749002-de6a533c64db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"
className="img-fluid"
style={{
width: "150px",
borderRadius: "50%",
marginTop: "30px",
}}
/>
</div>
<div className="row" style={{ marginTop: "2em", flex: "1" }}>
<div className="col-lg-12 text-center">
<h7 style={{ fontWeight: "bold" }}>{this.props.user.name}</h7>
</div>
<div className="col-lg-12 text-center">
<h7 style={{ color: "#9b9b9b" }}>{this.props.user.username}</h7>
</div>
<div className="col-lg-12 text-center">
<h7 style={{ color: "#9b9b9b" }}>Joined: {formattedDate}</h7>
</div>
<div
style={{ marginTop: "30px" }}
className="col-lg-4 text-center"
>
<h7 style={{ color: "#9b9b9b" }}>Spent:</h7>
</div>
<div
style={{ marginTop: "30px" }}
className="col-lg-4 text-center"
>
<h7 style={{ color: "#9b9b9b" }}>Items:</h7>
</div>
<div
style={{ marginTop: "30px" }}
className="col-lg-4 text-center"
>
<h7 style={{ color: "#9b9b9b" }}>Orders:</h7>
</div>
<div
style={{ marginTop: "10px" }}
className="col-lg-4 text-center"
>
<h7 style={{ fontWeight: "bold" }}>${infoObj.total.toFixed(2)}</h7>
</div>
<div
style={{ marginTop: "10px" }}
className="col-lg-4 text-center"
>
<h7 style={{ fontWeight: "bold" }}>{infoObj.itemsLen}</h7>
</div>
<div
style={{ marginTop: "10px" }}
className="col-lg-4 text-center"
>
<h7 style={{ fontWeight: "bold" }}>{infoObj.orderLength}</h7>
</div>
</div>
</div>
</div>
<div className="col-lg-8">
<div className="card p-card" style={{marginBottom:"5rem" }}>
<div className="col-lg-12">
<h6 style={{ fontWeight: "bold", marginBottom:'1rem'}}>My Orders:</h6>
</div>
<div className="col-lg-12">
<Table orders={this.props.user.orders}/>
</div>
</div>
{/* <div className="card p-card">
<div className="col-lg-12">
<h5 style={{ fontWeight: "bold" }}>Billing Info:</h5>
</div>
</div> */}
</div>
</div>
</div>
</FadeIn>
);
};
render() {
return (
<div className="row">
<div className="col-lg-12">
<div
className={
"alert alert-danger " +
(this.state.errMsg.length == 0 ? "my-hide" : "")
}
role="alert"
>
{this.state.errMsg}
</div>
</div>
{this.props.user
?
this._renderProfile()
: !this.props.user && this.state.isLogin
? this._renderLogin()
: !this.props.user && this.state.isRegister
? this._renderRegister()
: this._renderOptions()}
</div>
);
}
}
|
package org.antem.myalarm.Alarm;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Database(entities = {Alarm.class}, version = 2, exportSchema = false)
abstract class AlarmDatabase extends RoomDatabase {
public abstract AlarmDao alarmDao();
private static volatile AlarmDatabase INSTANCE;
private static final int NUMBER_OF_THREADS = 4;
static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
static AlarmDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (AlarmDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context.createDeviceProtectedStorageContext(),
AlarmDatabase.class,
"alarm_database"
).fallbackToDestructiveMigration().build();
}
}
}
return INSTANCE;
}
}
|
{% extends 'base.html' %}
{% block meta %}
<title>Todolist Tugas 6 PBP</title>
{% endblock meta %}
{% block content %}
<!doctype html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia">
<style>
* {
color: #2e3c4d;
text-align: center;
}
h1.tes {
text-decoration-line: underline;
font-family: Sofia;
color:#1c329f;
background-color: transparent ;
border-color: transparent;
}
li {
width: 140px;
font-size: 24px;
padding: 10px;
border-radius: 4px;
color: white;
cursor: pointer;
position: absolute;
top : -35px;
right : 80px;
}
body {
background-image: url(https://img.freepik.com/free-vector/pastel-floral-botanical-yearly-calendar-printable-vector-template-set_53876-156418.jpg?w=900&t=st=1672870846~exp=1672871446~hmac=0fd6739bc53fb069ba9a3002e0a9528bf138ca35fe5d32bcaf0945dcaa8da8aa);
background-size: 100;
}
.done {
background-color: rgba(3, 61, 30, 0.35);
border-color: transparent;
}
.create {
font-weight: 1000;
color:rgba(255, 255, 255, 0.966);
background-color: #767ae4be;
border-color: transparent;
box-shadow: 0px 0px 20px rgba(128, 128, 128, 0.3);
}
.logout {
background-color: rgba(255, 255, 255, 0.112);
color: #234063;
}
.date{
font-size: x-small;
}
.delete {
background-color:#0000002d;
border-color:transparent;
}
.modal-background-color {
border-color: transparent;
width: 300px;
padding: 1em;
}
</style>
<nav class="navbar navbar navbar-expand-lg navbar-light ">
<div class="container-fluid">
<a class="navbar-brand" href="#"> Name : {{ username }} </a>
<a class="btn btn-primary logout" href="{% url 'todolist:logout_user' %}">Logout</a>
</div>
</nav>
<body>
<div style="padding-top: 1%; padding-bottom: 3%;" >
<h1 class="tes"> ToDoList </h1>
</div>
<!-- Button trigger modal -->
<li><button type="button" class="btn btn-primary mb-5 create" data-bs-toggle="modal" data-bs-target="#FormModal" >Add Task </button></li>
</body>
<!-- Modal -->
<div class="modal" id="FormModal" aria-labelledby="FormModalLabel" >
<div class="modal-dialog modal-background-color">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="FormModalLabel">Add new task</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cancel"></button>
</div>
<div class="modal-body" style="text-align:left;">
{% csrf_token %}
<label>Title:</label><br>
<input id="title" class="appearance-none border rounded py-2 px-2 mx-1 " type="text" name="title" placeholder="Title"><br>
<label>Description:</label><br>
<input id="description" class="appearance-none border rounded py-2 px-2 mx-1 " type="description" name="description" placeholder="Task Description">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button id="add_btn" type="button" class="btn btn-primary create" id="add-task" data-bs-dismiss="modal">Add</button>
</div>
</div>
</div>
</div>
</body>
<div class="row" id="todolist"></div>
<script>
$(document).ready(function(){
$.get("/todolist/json/", function(data) {
for (i=0; i<data.length; i++){
$("#todolist").append(`
<div id="${data[i].id}" class="col-md-5 col-lg-3 mb-3">
<div class="card">
<div class="card-body column">
<h5 class="card-title">${data[i].fields.title}</h5>
<p class="card-text date">${data[i].fields.date}</p>
<p class="card-text">${data[i].fields.description}</p>
<div class="mt-auto">
<a href="/todolist/delete/${data[i].pk}" class="btn btn-primary delete mb-2">Delete</a>
${data[i].fields.is_finished ?
`<a href="/todolist/update/${data[i].pk}" class="btn btn-primary done mb-2">Done</a>` :
`<a href="/todolist/update/${data[i].pk}" class="btn btn-danger mb-2">Update</a>`}
</div>
</div>
</div>
</div>`)
}
});
$("#add_btn").click(function(){
$.post("/todolist/add/", {
title: $("#title").val(),
description: $("#description").val()
},
function(res){
$("#todolist").append(`
<div id="${res.id}--task" class="col-md-5 col-lg-3 mb-3">
<div class="card">
<div class="card-body ">
<h5 class="card-title">${res.fields.title}</h5>
<p class="card-text mb-1 date">${res.fields.date}</p>
<p class="card-text">${res.fields.description}</p>
<div class="mt-auto">
<a href="/todolist/delete/${res.id}" class="btn btn-primary delete" >Delete</a>
${res.fields.is_finished ?
`<a href="/todolist/update/${res.id}" class="btn btn-primary done">Done</a>` :
`<a href="/todolist/update/${res.id}" class="btn btn-danger ">Update</a>`}
</div>
</div>
</div>
</div>`);
}
)
})
});
</script>
{% endblock content %}
|
<template>
<div class="userlogin" v-loading="loading">
<Verify @success="verifySuccess" :mode="'pop'" :captchaType="'blockPuzzle'"
:imgSize="{ width: '330px', height: '155px' }" ref="verify" />
<el-form ref="loginForm" :rules="loginRules" :model="loginForm" class="login-form" status-icon label-width="0">
<el-form-item prop="username">
<el-input v-model="loginForm.username" size="small" autocomplete="off" placeholder="请输入用户名"
@keyup.enter.native="handleLogin">
<!-- <i slot="prefix" class="icon-yonghuming" /> -->
<div class="cus-icon-user" slot="prefix"></div>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input :type="passwordType" v-model="loginForm.password" autocomplete="off" size="small" placeholder="请输入密码"
@keyup.enter.native="handleLogin">
<i slot="suffix" class="el-icon-view el-input__icon" @click="showPassword" />
<div class="cus-icon-pwd" slot="prefix"></div>
<!-- <i slot="prefix" class="icon-mima"></i> -->
</el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" size="small" class="login-submit" @click.native.prevent="handleLogin">登录</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { randomLenNum } from '@/util/util'
import { mapGetters } from 'vuex'
import { getCode } from '@/api/code'
import Verify from '@/components/verifition/Verify'
export default {
name: 'Userlogin',
components: {
Verify,
},
data() {
return {
socialForm: {
code: '',
state: '',
},
loading: false,
loginForm: {
username: '',
password: '',
code: '',
randomStr: 'blockPuzzle',
},
checked: false,
code: {
src: undefined,
len: 4,
},
loginRules: {
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, message: '密码长度最少为6位', trigger: 'blur' },
],
},
passwordType: 'password',
}
},
computed: {
...mapGetters(['tagWel']),
},
methods: {
showPassword() {
this.passwordType == '' ? (this.passwordType = 'password') : (this.passwordType = '')
},
handleLogin() {
this.$refs.loginForm.validate((valid) => {
if (valid) {
this.$refs.verify.show()
}
})
},
verifySuccess(params) {
this.loading = true
this.loginForm.code = params.captchaVerification
this.$store
.dispatch('LoginByUsername', this.loginForm)
.then(() => {
this.loading = false
this.$router.push({ path: this.tagWel.value })
})
.catch(() => {
this.loading = false
})
},
},
}
</script>
<style lang="less" scoped>
.userlogin {
position: relative;
}
/deep/.el-icon-view {
margin: 0 10px;
}
</style>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link href="https://fonts.googleapis.com/css?family=Monoton|Source+Sans+Pro" rel="stylesheet">
</head>
<body>
<header>
<nav>
<ul>
<li class="botones"><a href="index.html">HTML5</a></li>
<li class="botones"><a href="css3.html">CSS3</a></li>
<li class="botones"><a href="java.html">JAVASCRIPT</a></li>
<li class="botones"><a href="jquery.html">JQUERY</a></li>
<li class="botones"><a href="contacto.html">CONTACTO</a></li>
</ul>
</nav>
</header>
<div class="titulo-principal">
<h1>HTML5</h1>
</div>
<div>
<section>
<div>
<article>
<h2>HTML5</h2>
<p>HyperText Markup Language, versión 5) es la quinta revisión importante del lenguaje básico de la World Wide Web, HTML. HTML5 especifica dos variantes de sintaxis para HTML: un «clásico» HTML (text/html), la variante conocida como HTML5 y una variante XHTML conocida como sintaxis XHTML5 que deberá ser servida como XML (XHTML) (application/xhtml+xml).1 2 Esta es la primera vez que HTML y XHTML se han desarrollado en paralelo.</p>
<p>Todavía se encuentra en modo experimental, lo cual indica la misma W3C; aunque ya es usado por múltiples desarrolladores web por sus avances, mejoras y ventajas.</p>
<h2>Nuevos elementos</h2>
<p>HTML5 establece una serie de nuevos elementos y atributos que reflejan el uso típico de los sitios web modernos. Algunos de ellos son técnicamente similares a las etiquetas div y span, pero tienen un significado semántico, como por ejemplo nav (bloque de navegación del sitio web) y footer. Otros elementos proporcionan nuevas funcionalidades a través de una interfaz estandarizada, como los elementos audio y video.</p>
<p>Al no ser reconocido en viejas versiones de navegadores por sus nuevas etiquetas, se le recomienda al usuario común actualizar a la versión más nueva, para poder disfrutar de todo el potencial que provee HTML5."</p>
<img src="img/html.png" alt="No cargó" title="HTML5 LOGO">
</article>
</div>
</section>
</div>
<div><aside>
<h2>DESCARGAS</h2>
<div><ul id="descargas">
<li><a href="descarga/archivo.docx"><img src="img/word.png" style="width:120px;height:120px;"></a></li>
<li><a href="descarga/archivo.jpg"><img src="img/imagen.png" style="width:120px;height:120px;"></a></li>
<li><a href="descarga/archivo.pdf"><img src="img/pdf.png" style="width:120px;height:120px;"></a></li>
<li><a href="descarga/archivo.zip"><img src="img/zip.png" style="width:120px;height:120px;"></a></li>
</ul></div>
</aside></div>
<footer>
<p>Todos los derechos reservados © Miguel Yustiz</p>
</footer>
</body>
</html>
|
package DesignPattern.behavioral.cor.Impl2;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
public class Dollar10Dispenser implements DispenseChain{
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain = nextChain;
}
@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 10) {
int num = cur.getAmount() / 10;
int remainder = cur.getAmount() % 10;
System.out.println("dispense " + num + " $10");
if (remainder != 0)
this.chain.dispense(new Currency(remainder));
} else {
this.chain.dispense(cur);
}
}
}
|
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
/**
* print_python_list - prints some info
* @p: python object
*/
void print_python_list(PyObject *p)
{
Py_ssize_t i, j = 0;
PyObject *list;
i = (((PyVarObject *)(p))->ob_size);
printf("[*] Python list info\n");
printf("[*] Size of the Python List = %lu\n", i);
printf("[*] Allocated = %lu\n", (((PyListObject *)(p))->allocated));
while (j < i)
{
list = (((PyListObject *)(p))->ob_item[j]);
printf("Element %lu: %s\n", j, (char *)list->ob_type->tp_name);
j++;
}
}
/**
*print_python_bytes - prints bytes
*@p: python object
*/
void print_python_bytes(PyObject *p)
{
printf("[.] bytes object info\n");
if (strcmp(p->ob_type->tp_name, "bytes") != 0)
{
printf(" [ERROR] Invalid Bytes Object\n");
exit(0);
}
}
|
<template>
<div>
<a-row :gutter="20">
<a-col span="12">
<a-input
allow-clear
v-model:value="queryBase"
:placeholder="`输入${queryBaseType}:「0x开头」`"
>
<template #addonBefore>
<a-select v-model:value="queryBaseType">
<a-select-option value="钱包地址">钱包地址</a-select-option>
<a-select-option value="钱包私钥">钱包私钥</a-select-option>
</a-select>
</template>
</a-input>
</a-col>
<a-col span="12" v-show="store.tokenType === '合约代币'">
<a-input
allow-clear
v-model:value="contractAddress"
addonBefore="合约地址"
placeholder="输入代币的合约地址"
></a-input>
</a-col>
</a-row>
<a-row>
<a-col span="4">
<a-button type="primary" @click="queryBalance">
查询余额「{{ store.tokenType }}」
</a-button>
</a-col>
</a-row>
<a-row>
<a-col :span="6">
<a-statistic title="钱包地址" :value="address" />
</a-col>
</a-row>
<a-row>
<a-col :span="6">
<a-statistic
:title="`钱包余额「${store.tokenType}」`"
:value="balance"
/>
</a-col>
</a-row>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import store from "../../stores/store";
import { abi, convertDecimalsToUnit, message } from "../../common";
export default defineComponent({
data() {
return {
//全局状态变量
store: store(),
//合约地址
contractAddress: ref<string>(""),
//「钱包地址」或「钱包私钥」类型
queryBaseType: ref<string>("钱包地址"),
//根据钱包地址或钱包私钥类型来查询
queryBase: ref<string>(""),
//余额
balance: ref<string>(""),
//合约代币精度
decimals: ref<string>("0"),
};
},
computed: {
//Web3对象
web3() {
return this.store.web3;
},
//Wei转换
fromWei() {
return this.store.web3.utils.fromWei;
},
//合约对象
contract() {
return this.store.getContract(abi, this.contractAddress);
},
address() {
if (this.queryBaseType === "钱包地址") {
if (this.queryBase.length === 42) {
return this.queryBase;
}
return "0x";
} else {
try {
return this.web3.eth.accounts.privateKeyToAccount(this.queryBase)
.address;
} catch (_) {
return "0x";
}
}
},
//根据合约小数位数转换为以太单位
unit() {
return convertDecimalsToUnit(this.decimals);
},
},
methods: {
//查询余额
queryBalance() {
this.query(this.address);
},
//查询
async query(address: string) {
this.balance = "0";
if (this.store.tokenType === "原生代币") {
this.web3.eth
.getBalance(address)
.then((balance: string) => {
this.balance = this.fromWei(balance, "ether");
})
.catch(() => {
message("warning", "余额查询", "查询失败,重新查询");
});
} else {
//获取合约代币精度
try {
this.decimals = await this.contract.methods.decimals().call();
} catch (_) {
message("warning", "余额查询", "合约信息获取失败,重新查询");
return;
}
this.contract.methods
.balanceOf(address)
.call()
.then((balance: string) => {
this.balance = this.fromWei(balance, this.unit);
})
.catch(() => {
message("warning", "余额查询", "查询失败,重新查询");
});
}
},
},
});
</script>
<style></style>
|
import { Component, Input, OnInit } from '@angular/core';
import { UserDTO } from "../../models/userDTO";
import { Utils } from "../../models/utils";
import { DatabaseService } from "../../services/database.service";
import { AlertService } from "../../services/alert.service";
import { updateUserParams } from "../../models/types";
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit{
@Input() user!: UserDTO;
hasActiveSubscription = "";
isCurrentUserSuspended: boolean | undefined;
constructor(private databaseService: DatabaseService,
private alertService: AlertService) {}
ngOnInit() {
this.hasActiveSubscription = "No information";
this.isCurrentUserSuspended = this.user.suspended
if (this.user.role == Utils.AdminRole) {
this.hasActiveSubscription = Utils.AdminRole;
} else {
this.databaseService.getSubscriptionForAGivenUser(this.user.id!).subscribe(res => {
if (res.length == 0 || this.user.suspended) {
this.hasActiveSubscription = "No"
} else {
res.map(subscription => {
subscription.start_date = subscription.start_date?.split('-').reverse().join('-');
subscription.end_date = subscription.end_date?.split('-').reverse().join('-');
const startDate = this.alertService.parseDate(subscription.start_date!);
const endDate = this.alertService.parseDate(subscription.end_date!);
const today = new Date();
today.setHours(0,0,0,0);
if (startDate != null && endDate != null) {
if (today >= startDate && today <= endDate) {
this.hasActiveSubscription = "Yes"
} else {
this.hasActiveSubscription = "No"
}
}
})
}
})
}
}
toggleSuspension(): void {
if (this.user.role == Utils.AdminRole) {
this.alertService.showAlert("Cannot suspend Admin accounts!");
this.isCurrentUserSuspended = !this.isCurrentUserSuspended;
return
}
const updateParameters: updateUserParams = {
id: this.user.id!,
suspended: (!this.isCurrentUserSuspended).toString()
}
this.databaseService.updateUser(updateParameters).subscribe(res => {
if (res.suspended) {
this.alertService.showAlertWithRefresh(`${res.email} was suspended!`)
} else {
this.alertService.showAlertWithRefresh(`${res.email} was UN-suspended!`)
}
})
}
deleteUser(): void {
if (this.user.role == Utils.AdminRole) {
this.alertService.showAlert("Cannot delete Admin accounts!");
return;
}
this.alertService.confirmAlert(`Are you sure you want to delete this user: ${this.user.email}?`).subscribe((confirmed: boolean) => {
if (confirmed) {
this.databaseService.deleteUser(this.user.id!).subscribe({
next: res => {
this.alertService.showAlertWithRefresh(`User: ${res.email} successfully deleted!`)
},
error: error => {
this.alertService.showAlert(error.statusText);
}})
}
});
}
}
|
package com.magp.creditformfiller.service;
import com.magp.creditformfiller.dao.ClientRepository;
import com.magp.creditformfiller.entity.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class ClientServiceImpl implements ClientService {
ClientRepository clientRepository;
@Autowired
public ClientServiceImpl(ClientRepository clientRepository) {
this.clientRepository = clientRepository;
}
@Override
public List<Client> findAll() {
// return clientRepository.findAll();
// Obtener el nombre de usuario del usuario autenticado
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = "";
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
} else {
username = principal.toString();
}
// Obtener los clientes que tienen el mismo nombre de usuario
return clientRepository.findByUser(username);
}
@Override
public Page<Client> findAllPaging() {
// Obtener el nombre de usuario del usuario autenticado
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = "";
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
} else {
username = principal.toString();
}
// Configurar la paginación
Pageable pageable = PageRequest.of(0, 4);
// Obtener los clientes que tienen el mismo nombre de usuario con paginación
return clientRepository.findByUser(username, pageable);
}
@Override
public Page<Client> findAllPaging(int currentPage) {
// Obtener el nombre de usuario del usuario autenticado
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = "";
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
} else {
username = principal.toString();
}
// Configurar la paginación
Pageable pageable = PageRequest.of(currentPage -1 , 4);
// Obtener los clientes que tienen el mismo nombre de usuario con paginación
return clientRepository.findByUser(username, pageable);
}
@Override
public Page<Client> findAllPaging(int currentPage, String sortField, String sortOrder) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = "";
if (principal instanceof UserDetails) {
username = ((UserDetails) principal).getUsername();
} else {
username = principal.toString();
}
Sort sort = Sort.by(sortOrder.equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC, sortField);
Pageable pageable = PageRequest.of(currentPage - 1, 4, sort);
return clientRepository.findByUser(username, pageable);
}
@Override
public Client findById(int id) {
Optional<Client> result = clientRepository.findById(id);
Client client = null;
if (result.isPresent()) {
client = result.get();
}
else {
// we didn't find the employee
throw new RuntimeException("Did not find employee id - " + id);
}
return client;
}
@Override
public void save(Client client) {
// clientRepository.save(client);
// Obtener el nombre de usuario del usuario autenticado
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = "";
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
} else {
username = principal.toString();
}
// Asignar el nombre de usuario al cliente
client.setUser(username);
// Guardar el cliente en la base de datos
clientRepository.save(client);
}
@Override
public void deleteById(int id) {
// clientRepository.deleteById(id);
Client cliente = clientRepository.findById(id).orElse(null);
if (cliente != null) {
// Obtener el nombre de usuario del usuario autenticado
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = "";
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
} else {
username = principal.toString();
}
// Verificar que el usuario sea el mismo que registró al cliente
if (cliente.getUser().equals(username)) {
// Eliminar el cliente de la base de datos
clientRepository.delete(cliente);
} else {
// Lanzar una excepción o mostrar un mensaje de error
}
} else {
// Lanzar una excepción o mostrar un mensaje de error
}
}
}
|
using GraphQLDemo.API.Entities;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace GraphQLDemo.API.Infrastructure.Configuration;
public class StudentCourseConfiguration : IEntityTypeConfiguration<StudentCourse>
{
public void Configure(EntityTypeBuilder<StudentCourse> builder)
{
builder.ToTable("StudentsCourses");
builder.HasKey(sc => new
{
sc.StudentId,
sc.CourseId
});
builder.HasIndex(sc => sc.StudentId)
.HasDatabaseName("IDX_StudentId_StudentsCourses");
builder.HasIndex(sc => sc.CourseId)
.HasDatabaseName("IDX_CourseId_StudentsCourses");
builder.Property(sc => sc.StudentId)
.HasColumnType("UNIQUEIDENTIFIER")
.HasColumnName("StudentId")
.ValueGeneratedOnAdd();
builder.Property(sc => sc.CourseId)
.HasColumnType("UNIQUEIDENTIFIER")
.HasColumnName("CourseId")
.ValueGeneratedOnAdd();
// FKs
builder.HasOne(sc => sc.Student)
.WithMany(s => s.StudentsCourses)
.HasForeignKey(sc => sc.StudentId);
builder.HasOne(sc => sc.Course)
.WithMany(s => s.StudentsCourses)
.HasForeignKey(sc => sc.CourseId);
}
}
|
//线程池--解决同一时间的大量请求
//线程早先创建 线程有上线
#ifndef __THREADPOOL_HPP__
#define __THREADPOOL_HPP__
#include <iostream>
#include <queue>
#include <pthread.h>
typedef void (*handler_t)(int);
class Task{
private:
int sock;
handler_t handler;
public:
Task(int sock_,handler_t handler_):sock(sock_),handler(handler_)
{}
void Run(){
handler(sock);
}
~Task(){
}
};
class ThreadPool{
private:
int num; //线程个数
int idle_num; //休眠线程数
std::queue<Task> task_queue; //任务队列
pthread_mutex_t lock; //锁
pthread_cond_t cond; //唤醒线程
public:
ThreadPool(int num_):num(num_),idle_num(0){
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
}
void InitThreadPool(){
pthread_t tid;
for(auto i = 0;i < num; i++){
pthread_create(&tid,NULL,ThreadRoutine,(void*)this);
}
}
bool IsTaskQueueEmpty(){
return task_queue.size() == 0 ?true : false;
}
void LockQueue(){
pthread_mutex_lock(&lock);
}
void UnlockQueue(){
pthread_mutex_unlock(&lock);
}
void Idle(){
idle_num++;
pthread_cond_wait(&cond,&lock);
idle_num--;
}
void Wakeup(){
pthread_cond_signal(&cond);
}
Task PopTask(){
Task t = task_queue.front();
task_queue.pop();
return t;
}
void PushTask(Task &t){
LockQueue();
task_queue.push(t);
UnlockQueue();
Wakeup(); //唤醒
}
static void *ThreadRoutine(void *arg){
pthread_detach(pthread_self());
ThreadPool *tp = (ThreadPool*)arg;
for(;;){
tp->LockQueue();
while(tp->IsTaskQueueEmpty()){
tp->Idle();
}
Task t = tp->PopTask();
tp->UnlockQueue();
std::cout << "task is handler by: " << pthread_self() << std::endl;
t.Run();
}
}
~ThreadPool(){
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
}
};
//单例
class singleton{
private:
static ThreadPool *p;
static pthread_mutex_t lock;
public:
static ThreadPool *GetInstance(){
//懒汉模式
if(NULL == p){
pthread_mutex_lock(&lock);
if(NULL == p){
p = new ThreadPool(5);
p->InitThreadPool();
}
pthread_mutex_unlock(&lock);
}
return p;
}
};
ThreadPool *singleton::p = NULL;
pthread_mutex_t singleton::lock = PTHREAD_MUTEX_INITIALIZER; //用这个宏定义全局锁,不要初始化,释放
#endif
|
package yingjianhua.vote.tools.mch;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import yingjianhua.vote.bean.WxAccount;
import yingjianhua.vote.pub.Log;
import yingjianhua.vote.pub.PubInfs.IMsg;
/**
* 商户平台调用工具
* @author yingjianhua
*
*/
public abstract class MchUtil {
private static final Log LOG = new Log(MchUtil.class);
public enum Msgs implements IMsg {// 信息定义的类名必须为Msgs, 以便系统能检索 @formatter:off
CertErr("商户平台证书错误!"),
;
private String _msg;
private Msgs(String msg) { _msg=msg; }
public String getMsg() {return _msg; }
} //@formatter:on
private static final String ALLCHAR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String ALLNUM = "0123456789";
private static final Random random = new Random();
/**
* 生成长度为 length 的随机字符串,包含数字和大写字母
* @param length
* @return
*/
public static final String createRandom(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
}
return sb.toString();
}
/**
* 生成长度为 length 的随机字符串,包含数字
* @param length
* @return
*/
public static final String createRandomNum(int length) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(ALLNUM.charAt(random.nextInt(ALLNUM.length())));
}
return sb.toString();
}
/**
* 对字符串进行MD5运算
* @param str
* @return
* @throws NoSuchAlgorithmException
*/
public static String md5(String str) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("MD5");
try {
digest.update(str.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder md5 = new StringBuilder();
int i;
for(byte line:digest.digest()) {
i = line;
if(i < 0) {
i+=256;
}
if(i < 16) {
md5.append("0");
}
md5.append(Integer.toHexString(i).toUpperCase());
}
System.out.println(md5.toString().toUpperCase()+" length:"+md5.toString().length());
return md5.toString().toUpperCase();
}
/**
* 生成随机字符串
* @param length
* @return
*/
protected String createNonceStr(int length) {
return createRandom(length);
}
/**
* 计算签名
* @param mchKey
* @return
* @throws NoSuchAlgorithmException
*/
protected String createSign(String mchKey) throws NoSuchAlgorithmException {
Field[] fields = this.getClass().getDeclaredFields();
StringBuffer buffer = new StringBuffer();
Map<String, Object> map = new TreeMap<String, Object>();
for(Field field:fields) {
try {
if(field.getAnnotation(Sendable.class) != null) {
if(field.get(this)==null) continue;
map.put(field.getName(), field.get(this));
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
for(String key:map.keySet()) {
buffer.append(key+"="+map.get(key)+"&");
}
String stringSignTemp = buffer+"key="+mchKey;
System.out.println(stringSignTemp);
return md5(stringSignTemp);
}
/**
* 讲field转换成xml格式
* @return
*/
protected String trans2XML() {
Field[] fields = this.getClass().getDeclaredFields();
StringBuffer buffer = new StringBuffer();
buffer.append("<xml>\r\n");
for(Field field:fields) {
System.out.println(field.getName());
try {
if(field.getAnnotation(Sendable.class) != null){
if(field.get(this)==null) continue;
buffer.append("<"+field.getName()+">");
buffer.append(field.get(this));
buffer.append("</"+field.getName()+">\r\n");
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
buffer.append("</xml>");
return buffer.toString();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sendable {
}
}
|
namespace ShopperBackend.Middlewares
{
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
private readonly string _id;
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger, string id)
{
_next = next;
_logger = logger;
_id = id;
}
public async Task InvokeAsync(HttpContext context)
{
// Log the request details with ID
_logger.LogInformation($"Middleware {_id} - Incoming request: {context.Request.Method} {context.Request.Path}");
// Call the next middleware in the pipeline
await _next(context);
// Log the response details with ID
_logger.LogInformation($"Middleware {_id} - Outgoing response: {context.Response.StatusCode}");
}
}
}
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Lesson extends Model
{
use HasFactory;
protected $table = 'lesson';
protected $fillable = [
'id',
'name',
'video_path',
'duration',
'description',
'is_preview',
'status',
'ordinal_number',
'module_id',
'analysis_text_result_json',
'analysis_video_result_json'
];
public function userLessons(): HasMany
{
return $this->hasMany(UserLesson::class, 'lesson_id');
}
public function getFinishTime(int $userId)
{
$userLesson = $this->userLessons()->where('user_id', $userId)->first();
return $userLesson ? $userLesson->completed_at : null;
}
}
|
# Shutter

Hello Engineer, firstly thank you so much for your time in reviewing this project. I look forward to discussing more technical decisions in detail 👋🏼👋🏼👋🏼
## Table of content
- [Prerequisite](#prerequisite)
- [Preview](#preview)
- [Requirement](#feature)
- [Design](#design)
- [Architecture](#architecture)
- [Testing](#testing)
- [Improvement](#improvement)
## Prerequisite
- Android Studio Arctic Fox | 2020.3.1
- Gradle version 7.1.0
- MinSdk 21
- TargetSdk 32
## Preview
<img src="https://user-images.githubusercontent.com/61085272/196795375-fc9a71bf-a1a1-4cdd-ba39-4e721dce0cbb.jpg" width="33%" /> <img src="https://user-images.githubusercontent.com/61085272/196795428-5f7e5b40-4624-4a7c-92db-ed71962e3e7b.jpg" width="33%" />
## Requirement
```
Please implement an app that can search for pictures from the Shutterstock API (https://apireference.shutterstock.com/ ) and displays them in an infinite scrollable view.
Main focus should be on a highly performant app (smooth scrolling & lag-free UI) and
on testing(unit/UI) feasible parts.
```
## Design
- Constraint layouts were also used to prevent nested views and ensure layouts rendered in less than 60 frames per second which prevents UI jank
- Made consideration for An architecture(MVVM) which will ensure separation of concerns. Preventing memory leaks, threading issues while also testable and scalable
- For seamless scrolling I chose to use the paging library for pagination
## Architecture
The application follows clean architecture because of the benefits it brings to software which includes scalability, maintainability and testability.
It enforces separation of concerns and dependency inversion, where higher and lower level layers all depend on abstractions. In the project, the layers are separated into different layers namely:
- Data Layer
- Domain Layer
- Presentation Layer
### Data Layer
The data layer contains application data and business logic. The business logic is what gives value to your app—it's made of real-world business rules that determine how application data must be created, stored, and changed.
#### Remote layer
The remote later relies on Retrofit library to fetch data from the API. .
#### Paging Source
This helps load data from a data source into a snapshot of pages. Ensuring that your app uses network bandwidth and system resources efficiently.
#### Repository
My repository was used to expose data to the rest of the application and also reolving conflicts. Helped in Abstracting sources of data from the rest of the app.
### Presentation
The UI/Presentation layer is the pipeline that converts application data-changes to a form that the UI can present and then displays it. I used a pattern where state of the application flows down and events flow up called `Unidirectional data flow`. Here the view model holds and exposes the state in an observable data holder called `LiveData`. This ensures quick retoration of state after configuration changes. Also the UI can react to any changes made in the state without having to manually pull data directly from the ViewModel.
The UI notifies the ViewModel of user events and data requests.
The ViewModel handles the actions and updates the state.
The updated state is fed back to the UI to render.
The above is repeated for any event that causes a mutation of state.
## Testing
Testing is done with Junit4 testing framework for assertions and Mockito for mocking classes. Each layer has its own test.
Viewmodel tests verify that each call to repository produces the correct view state.
PagingSource Test verify each interaction with server returns the expected result.
## Improvement
- App should be made to operate offline first because network availability is not always guaranteed
- I also will be grateful to hear your feedback/criticism so I can improve and make better decisions next time.
## - Built With 🛠
- [Kotlin](https://kotlinlang.org/) - First class and official programming language for Android development.
- [Android Architecture Components](https://developer.android.com/topic/libraries/architecture) - Collection of libraries that help you design robust, testable, and maintainable apps.
- [StateFlows](https://developer.android.com/kotlin/flow) - Flow APIs that enable flows to optimally emit state updates and emit values to multiple consumers.
- [ViewModel](https://developer.android.com/topic/libraries/architecture/viewmodel) - Stores UI-related data that isn't destroyed on UI changes.
- [LiveData] -Lifecycle aware data holder
- [Retrofit](https://square.github.io/retrofit/) - A type-safe HTTP client for Android and Java.
- [OkHttp](http://square.github.io/okhttp/) - HTTP client that's efficient by default: HTTP/2 support allows all requests to the same host to share a socket
- [Glide](https://github.com/bumptech/glide) - image loading framework for Android
- [Gson](https://github.com/google/gson) - used to convert Java Objects into their JSON representation and vice versa.
- [Mockito](http://site.mockito.org/) - Most popular mocking framework for Java/kotlin.
|
import { useDispatch, useSelector } from "react-redux";
import { openCartSidebar, openSearchBox } from "../../features/toggle/toggleSlice";
import { selectorCart } from "../../features/cart/cartSlice";
import { selectorAuth, signOutLocalStorage } from "../../features/auth/authSlice";
import { FiUserPlus, FiUserMinus } from "react-icons/fi";
import { IoBagHandleOutline, IoSearchOutline } from "react-icons/io5";
import { Link } from 'react-router-dom';
const ActionNavbar = () => {
const dispatch = useDispatch();
const { total_items } = useSelector(selectorCart);
const { myUser } = useSelector(selectorAuth);
return (
<ul className="flex items-center gap-x-3 md:gap-x-6">
<li>
<div className="relative">
<button
aria-label="open view cart"
className="block"
onClick={() => dispatch(openCartSidebar())}
>
<IoBagHandleOutline className="w-7 h-7" />
</button>
<div className="absolute -top-2 -right-2.5 bg-primary w-5 h-5 rounded-full flex items-center justify-center">
<span className="block font-bold text-xs">{total_items}</span>
</div>
</div>
</li>
<li>
<div>
<button
type="button"
aria-label="search"
onClick={() => dispatch(openSearchBox())}
className="block"
>
<IoSearchOutline className="w-7 h-7" />
</button>
</div>
</li>
{myUser === true ? (
<li>
<div>
<button
type="button"
aria-label="sign out"
onClick={() => dispatch(signOutLocalStorage())}
className="block"
>
<div className="flex items-end gap-x-1">
<FiUserMinus className="w-7 h-7" />
<div className="hidden lg:inline-flex">Logout</div>
</div>
</button>
</div>
</li>
) : (
<li>
<Link to='/signin'>
<div className="flex items-end gap-x-1">
<FiUserPlus className="w-7 h-7" />
<div className="hidden lg:inline-flex">Login</div>
</div>
</Link>
</li>
)}
</ul>
)
}
export default ActionNavbar
|
import React, {FunctionComponent} from 'react';
import {View, Text} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import styles from './ListTile.style';
interface Props {
title: string;
subtitle: string;
icon: string;
}
const ListTile: FunctionComponent<Props> = ({title, subtitle, icon}) => {
return (
<View style={styles.container}>
<Icon name={icon} size={45} />
<View style={styles.text_container}>
<Text style={styles.title}>{title}</Text>
<Text style={styles.subtitle}>{subtitle}</Text>
</View>
</View>
);
};
export default ListTile;
|
!! Copyright(C) Stichting Deltares, 2012.
!!
!! This program is free software: you can redistribute it and/or modify
!! it under the terms of the GNU General Public License version 3,
!! as published by the Free Software Foundation.
!!
!! 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/>.
!!
!! contact: delft3d.support@deltares.nl
!! Stichting Deltares
!! P.O. Box 177
!! 2600 MH Delft, The Netherlands
!!
!! All indications and logos of, and references to registered trademarks
!! of Stichting Deltares remain the property of Stichting Deltares. All
!! rights reserved.
subroutine nralgs ( pmsa , fl , ipoint , increm , noseg ,
& noflux , iexpnt , iknmrk , noq1 , noq2 ,
& noq3 , noq4 )
!>\file
!> Nutrient release of algae in S1 and S2
C**********************************************************************
C +----------------------------------------+
C | D E L F T H Y D R A U L I C S |
C | WAter Resources and Environment |
C +----------------------------------------+
C
C***********************************************************************
C
C Project : STANDAARDISATIE PROCES FORMULES T721.72
C Author : Pascal Boderie
C Date : 921210 Version : 0.01
C
C History :
C
C Date Author Description
C ------ -------------- -----------------------------------
C ...... .............. ..............................
C 930730 Pascal Boderie Mortality of algae in sediment
C 073107 Jos van Gils Expanded with optional autolysis to Switch
C
C***********************************************************************
C
C Description of the module :
C
C Name T L I/O Description Unit
C ---- --- - - ------------------- ---
C FALGx R*4 1 I mortality flux of algea-type x in sediment [gC/m3/d]
C FL(1) R*4 1 O autolysis of NN4 [gN/m3/d]
C FL(2) R*4 1 O production of N-det [gN/m3/d]
C FL(3) R*4 1 O autolysis of P [gP/m3/d]
C FL(4) R*4 1 O production of P-det [gP/m3/d]
C FL(5) R*4 1 O autolysis of Si [gSi/m3/d]
C FL(6) R*4 1 O production of Si-det [gSiC/m3/d]
C FRMRT1 R*4 1 I fraction of mortality dissolved as nutrients [-]
C FRMRT2 R*4 1 I fraction of mortality dissolved as nutrients [-]
C NCRAT1 R*4 1 I Nitrogen-Carbon ratio in green-algea [gN/gC]
C NCRAT2 R*4 1 I Nitrogen-Carbon ratio in diatoms [gN/gC]
C PCRAT1 R*4 1 I Phosphorus-Carbon ratio in green-algea [gP/gC]
C PCRAT2 R*4 1 I Phosphorus-Carbon ratio in diatoms [gP/gC]
C SICRAT R*4 1 I Silicate-Carbon ratio in diatoms [gSi/gC]
C Logical Units : -
C Modules called : -
C Name Type Library
C ------ ----- ------------
IMPLICIT NONE
REAL PMSA ( * ) , FL (*)
INTEGER IPOINT( * ) , INCREM(*) , NOSEG , NOFLUX,
+ IEXPNT(4,*) , IKNMRK(*) , NOQ1, NOQ2, NOQ3, NOQ4
integer ip1 , ip2 , ip3 , ip4 , ip5 , ip6 , ip7 , ip8 ,
j ip9 , ip10, ip11, ip12, ip13,
j iflux, iseg, ikmrk1, ikmrk2
real FALG1,NCRAT1,PCRAT1,AUT1,DET1,FALG2,NCRAT2,PCRAT2,
j SICRAT,AUT2,DET2,DEPTH,SWITCH,AA,DC1,DC2
C
IP1 = IPOINT( 1)
IP2 = IPOINT( 2)
IP3 = IPOINT( 3)
IP4 = IPOINT( 4)
IP5 = IPOINT( 5)
IP6 = IPOINT( 6)
IP7 = IPOINT( 7)
IP8 = IPOINT( 8)
IP9 = IPOINT( 9)
IP10 = IPOINT(10)
IP11 = IPOINT(11)
IP12 = IPOINT(12)
IP13 = IPOINT(13)
C
IFLUX = 0
DO 9000 ISEG = 1 , NOSEG
!! CALL DHKMRK(1,IKNMRK(ISEG),IKMRK1)
!! IF (IKMRK1.EQ.1) THEN
IF (BTEST(IKNMRK(ISEG),0)) THEN
CALL DHKMRK(2,IKNMRK(ISEG),IKMRK2)
IF ((IKMRK2.EQ.0).OR.(IKMRK2.EQ.3)) THEN
C
FALG1 = PMSA(IP1)
NCRAT1 = PMSA(IP2)
PCRAT1 = PMSA(IP3)
AUT1 = PMSA(IP4)
DET1 = PMSA(IP5)
FALG2 = PMSA(IP6)
NCRAT2 = PMSA(IP7)
PCRAT2 = PMSA(IP8)
SICRAT = PMSA(IP9)
AUT2 = PMSA(IP10)
DET2 = PMSA(IP11)
DEPTH = PMSA(IP12)
switch = PMSA(IP13)
C***********************************************************************
C**** Processes connected to the ALGEA model
C***********************************************************************
C Calculate fractions for carbon (different from nutrient fractions)
C no part of carbon to autolyse!
DC1 = 0.0
DC2 = 0.0
IF (AUT1 .LT. 1.0) DC1 = DET1 / (1-AUT1)
IF (AUT2 .LT. 1.0) DC2 = DET2 / (1-AUT2)
C@ Production of DETC
FL ( 1 + IFLUX ) = ( FALG1 * DC1+
& FALG2 * DC2 ) / DEPTH
C@ Production of OOC
FL ( 2 + IFLUX ) = ( FALG1 * ( 1.0 - DC1 ) +
& FALG2 * ( 1.0 - DC2 ) ) / DEPTH
C@ Autolysis of NN4
AA = ( FALG1 * NCRAT1 * AUT1 +
& FALG2 * NCRAT2 * AUT2 ) / DEPTH
if ( abs(switch) .lt. 0.5 ) then
FL ( 3 + IFLUX ) = AA
FL (12 + IFLUX ) = 0.0
else
FL (12 + IFLUX ) = AA
FL ( 3 + IFLUX ) = 0.0
endif
C@ Production of N-det
FL ( 4 + IFLUX ) = ( FALG1 * NCRAT1 * DET1 +
& FALG2 * NCRAT2 * DET2 ) / DEPTH
C@ Production of OON
FL ( 5 + IFLUX ) = ( FALG1 * NCRAT1 * ( 1.0 - AUT1 - DET1 ) +
& FALG2 * NCRAT2 * ( 1.0 - AUT2 - DET2 ) ) / DEPTH
C@ Autolysis of P
AA = ( FALG1 * PCRAT1 * AUT1 +
& FALG2 * PCRAT2 * AUT2 ) / DEPTH
if ( abs(switch) .lt. 0.5 ) then
FL ( 6 + IFLUX ) = AA
FL (13 + IFLUX ) = 0.0
else
FL (13 + IFLUX ) = AA
FL ( 6 + IFLUX ) = 0.0
endif
C@ Production of P-det
FL ( 7 + IFLUX ) = ( FALG1 * PCRAT1 * DET1 +
& FALG2 * PCRAT2 * DET2 ) / DEPTH
C@ Production of OOP
FL ( 8 + IFLUX ) = ( FALG1 * PCRAT1 * ( 1.0 - AUT1 - DET1 ) +
& FALG2 * PCRAT2 * ( 1.0 - AUT2 - DET2 ) ) / DEPTH
C@ Autolysis of Si
FL ( 9 + IFLUX ) = ( FALG2 * SICRAT * AUT2 ) / DEPTH
C@ Production of Si-det
FL (10 + IFLUX ) = ( FALG2 * SICRAT * DET2 ) / DEPTH
C@ Production of OOSi
FL (11 + IFLUX ) = ( FALG2 * SICRAT * (1.0 - AUT2 - DET2) ) /
& DEPTH
C
ENDIF
ENDIF
C
IFLUX = IFLUX + NOFLUX
IP1 = IP1 + INCREM ( 1 )
IP2 = IP2 + INCREM ( 2 )
IP3 = IP3 + INCREM ( 3 )
IP4 = IP4 + INCREM ( 4 )
IP5 = IP5 + INCREM ( 5 )
IP6 = IP6 + INCREM ( 6 )
IP7 = IP7 + INCREM ( 7 )
IP8 = IP8 + INCREM ( 8 )
IP9 = IP9 + INCREM ( 9 )
IP10 = IP10 + INCREM ( 10 )
IP11 = IP11 + INCREM ( 11 )
IP12 = IP12 + INCREM ( 12 )
IP13 = IP13 + INCREM ( 13 )
C
9000 CONTINUE
C
RETURN
END
|
import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate,useParams } from 'react-router-dom';
import { ReactComponent as Logo } from "../images/undraw_remotely_2j6y.svg";
function RegisterUsernamePassword() {
var regularExpression = new RegExp(/^[A-Za-z]\w{8,15}$/);
const navigate = useNavigate();
const {verificationToken} = useParams()
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
async function submitPatientRegister2(e) {
e.preventDefault();
if(username.length < 5 || username.length > 25 )
{
alert("Username should be between 5 to 25 characters!!")
return false;
}
else if(regularExpression.test(password))
{
alert("password should contain atleast one number and one special character");
return false;
}
else if(password.length < 8 || password.length > 15)
{
alert("Password should be between 8 to 15 characters!!")
return false;
}
if (password === confirmPassword) {
try {
const response = await axios.post('http://localhost:8000/patientRegister2', {
verificationToken, username, password,
});
if (response.data === 'registered') {
alert('Registration successful!');
navigate('/login');
}else if (response.data === 'exists'){
alert('Username already exists');
} else {
alert('Error registering username and password');
}
} catch (error) {
console.error('Error registering username and password:', error);
}
}
else {
alert('Passwords Mismatch.')
}
}
return (
<div className="PatientLogin-whole">
<div className="PatientLogin-left">
<div className="PatientLogin-logo ">Lifeline<span className="PatientLogin-logo-span">.</span> <span className="PatientLogin-logo-side">Confirm your Username and Password</span></div>
<Logo className="PatientLogin-image"/>
</div>
<div className="PatientLogin-right">
<form method="POST" action="/login" className="PatientLogin-form">
<div className="PatientLogin-username PatientLogin-input">
<label htmlFor="username">Username</label><b/>
<input type="text" placeholder="Username" name="username" onChange={(e) => { setUsername(e.target.value) }} required /><br/>
</div>
<div className="PatientLogin-password PatientLogin-input">
<label htmlFor="password">Password</label><b/>
<input type="password" placeholder="Password" name="password" onChange={(e) => { setPassword(e.target.value) }} required/><br/>
</div>
<div className="PatientLogin-password PatientLogin-input">
<label htmlFor="confirm-password">Confirm Password</label><b/>
<input type="password" placeholder="Confirm Password" name="confirm-password" onChange={(e) => { setConfirmPassword(e.target.value) }} required/><br/>
</div>
<input type="submit" onClick={submitPatientRegister2} className="PatientLogin-form-btn"/>
</form>
</div>
</div>
);
}
export default RegisterUsernamePassword;
|
package whackamole.whackamole.DB;
import whackamole.whackamole.Config;
import whackamole.whackamole.Logger;
import java.io.File;
import java.sql.*;
import org.codehaus.plexus.util.ExceptionUtils;
import org.jetbrains.annotations.Nullable;
public class SQLite {
private static String url = "jdbc:sqlite:" + Config.AppConfig.storageFolder+ "/Storage.db";
private SQLite() {}
private static SQLite Instance;
public static SQLite getInstance() {
if (SQLite.Instance == null) {
SQLite.Instance = new SQLite();
}
return SQLite.Instance;
}
public static void onLoad() {
var dbFile = new File(Config.AppConfig.storageFolder + "/Storage.db");
if(!dbFile.exists()) {
getGameDB().Create();
getGridDB().Create();
getCooldownDB().Create();
getScoreboardDB().Create();
}
}
public String getUrl() {
return SQLite.url;
}
public void setUrl(String url) {
SQLite.url = url;
}
private static Connection connection;
@Nullable
private static Connection getConnection() {
if (SQLite.connection == null) {
try {
SQLite.connection = DriverManager.getConnection(url);
} catch (SQLException e) {
Logger.error(e.getMessage());
Logger.error(e.getStackTrace().toString());
assert false : e.getMessage();
}
}
return SQLite.connection;
}
private PreparedStatement getStatement(String query, Object... arguments) throws SQLException {
var connection = getConnection();
var stmt = connection.prepareStatement(query);
for (int i = 0; i < arguments.length; i++) {
stmt.setObject(i + 1, arguments[i]);
}
return stmt;
}
public void executeUpdate(String query) {
this.executeUpdate(query, new Object[0]);
}
public void executeUpdate(String query, Object ... arguments) {
try {
var stmt = this.getStatement(query, arguments);
stmt.executeUpdate();
} catch (SQLException e) {
Logger.error("Failed to execute Query: (%s)\nFor Reason: %s\nWith StackTrace:\n%s".formatted(
query,
e.getMessage(),
ExceptionUtils.getStackTrace(e)
));
assert false : "Failed to execute Query: (%s)\nFor Reason: %s\nWith StackTrace:\n%s".formatted(
query,
e.getMessage(),
ExceptionUtils.getStackTrace(e));
}
}
@Nullable
public ResultSet executeQuery(String query) {
return this.executeQuery(query, new Object[0]);
}
@Nullable
public ResultSet executeQuery(String query, Object ... arguments) {
try {
var stmt = this.getStatement(query, arguments);
return stmt.executeQuery();
} catch (SQLException e) {
Logger.error("Failed to execute Query: (%s)\nFor Reason: %s\nWith StackTrace:\n%s".formatted(
query,
e.getMessage(),
ExceptionUtils.getStackTrace(e)));
assert false : "Failed to execute Query: (%s)\nFor Reason: %s\nWith StackTrace:\n%s".formatted(
query,
e.getMessage(),
ExceptionUtils.getStackTrace(e));
return null;
}
}
public static ScoreboardDB getScoreboardDB() { return new ScoreboardDB(getInstance()); }
public static CooldownDB getCooldownDB() { return new CooldownDB(getInstance()); }
public static GridDB getGridDB() { return new GridDB(getInstance()); }
public static GameDB getGameDB() { return new GameDB(getInstance()); }
}
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- Head element fragment with customizable title-->
<head>
<title>General template</title>
<th:block th:fragment="headerFragment">
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link th:href="@{/css/general.css}" rel="stylesheet"/>
<link th:href="@{/css/nav/main-header.css}" rel="stylesheet"/>
<link rel="icon" type="image/x-icon" th:href="@{/images/book-shelf-logo/png/yellow-logo.png}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.min.js"></script>
</th:block>
</head>
<!-- Head element fragment with customizable title-->
<body>
<!-- Navigation bar fragment -->
<div th:fragment="navigation-bar"
th:with="loggedUser=@{__${@thymeleaf.getCurrentUserPesel()}__}, emptyUser=@{__${@thymeleaf.getEmptyUser()}__}">
<div class="navigation">
<nav class="navbar navbar-expand-xl navbar-dark" id="main-nav-banner">
<a class="navbar-brand" th:href="@{/}">
<img id="main-nav-logo" th:src="@{/images/book-shelf-logo/png/logo-no-background.png}"
alt="Book Shelf Logo">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-between" id="navbarSupportedContent">
<div class="navbar-nav">
<div class="nav-item mt-2">
<form class="d-flex" id="global-search" th:action="@{/search}" method="get">
<input class="form-control" id="global-search-input"
th:placeholder="${#request.getParameter('query') != null ? #request.getParameter('query') : 'Search for titles and authors'}"
aria-label="Search" name="query" required>
<button id="global-search-button" class="btn" type="submit">
<i class="fa fa-search"></i>
</button>
</form>
</div>
</div>
<div class="navbar-nav" id="main-nav-buttons">
<div class="nav-item">
<a class="nav-link" th:href="@{/profile}">My profile</a>
</div>
<div class="nav-item dropdown">
<div class="nav-link dropdown-toggle" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Catalog
</div>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">My profile</a>
<a class="dropdown-item" href="#">My calendar</a>
<a class="dropdown-item" href="#">My appointments</a>
</div>
</div>
</div>
<div class="navbar-nav">
<div th:if="${loggedUser == emptyUser}" th:remove="tag">
<a class="btn main-login-button" th:href="@{/user-login}">
<i class="fa fa-sign-in" aria-hidden="true"></i> Log in
</a>
<a th:href="@{/register}" class="btn main-login-button">
<i class="fa fa-user-circle" aria-hidden="true"></i> Sign in
</a>
</div>
<div th:unless="${loggedUser == emptyUser}">
<a class="btn main-login-button" th:href="@{/user-logout}">
<i class="fa fa-sign-out" aria-hidden="true"></i> Log out
</a>
</div>
</div>
</div>
</nav>
</div>
</div>
<!-- Navigation bar fragment -->
</body>
</html>
|
<template>
<div>
<div v-if="products.length <= 0" class="container py-5 text-center" style="min-height: 75vh;">
<div>
<h3>You don't have products added in your Cart!</h3>
<a class="btn btn-outline-primary btn-lg" href="/category/1">Continue Shopping</a>
</div>
</div>
<div class="row justify-content-center">
<div class="col">
<div class="row align-items-center mb-3" v-for="product in products" :key="product.id">
<div class="col-4 col-md-3 col-lg-2">
<div class="image image-s">
<img class="image-cover" :src="product.media_a" :alt="product.data_product_group">
</div>
</div>
<div class="col">
<h5 class="m-0 mb-2">{{ product.data_product_group }}</h5>
<p class="m-0 mb-2">{{ product.product_group.brand }}</p>
<h4 class="m-0 mb-2">₹{{ product.rate }} <del class="fs-6 text-danger">MRP ₹{{ product.mrp }}</del></h4>
</div>
<div class="col-auto">
<div class="input-group input-group-sm mb-3" style="width:100px !important;">
<button @click="minus(product)" class="btn btn-outline-primary" type="button"><i class="fas fa-minus"></i></button>
<input type="text" class="form-control border-primary text-center" :value="product.data_cart">
<button @click="plus(product)" class="btn btn-outline-primary" type="button"><i class="fas fa-plus"></i></button>
</div>
<div class="input-group input-group-sm" style="width:100px !important;">
<button @click="deleteCartItem(product.id)" class="btn btn-danger w-100" type="button">Delete</button>
</div>
</div>
</div>
</div>
<div v-if="products.length > 0" class="col-10 col-lg-4 mb-4">
<ul class="list-group list-group-flush">
<li class="list-group-item text-bg-warning">{{ delivery_timing }}</li>
<li class="list-group-item">MRP Total <span class="float-right">{{ calc.mrp_total }}</span></li>
<li class="list-group-item">Cost Total <span class="float-right">{{ calc.cost_total }}</span></li>
<li class="list-group-item">Tax Total <span class="float-right">{{ calc.tax_total }}</span></li>
<li class="list-group-item">Rate Total <span class="float-right">{{ calc.rate_total }}</span></li>
<li class="list-group-item">Discount <span class="float-right">{{ calc.discount }}</span></li>
<li class="list-group-item">Delivery Charges <span class="float-right">{{ calc.delivery_charges }}</span></li>
<li class="list-group-item fw-bold">Payable <span class="float-right">{{ calc.payable }}</span></li>
<li v-if="calc.rate_total >= free_delivery_amount" class="list-group-item fw-bold">You are eligible for free delivery.</li>
<li v-if="calc.rate_total < free_delivery_amount" class="list-group-item fw-bold">Shop more Rs: {{ free_delivery_amount - calc.rate_total }}/- for Free Delivery.</li>
<li class="list-group-item">
<a href="/checkout" class="btn btn-primary w-100" :class="calc.canProceed ? '' : 'disabled'">Proceed</a>
</li>
<li v-if="!calc.canProceed" class="list-group-item fw-bold text-danger">
Minimum Order Amount is Rs: {{ minimum_order_amount }}/-
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['delivery_timing', 'buyqty', 'delivery_charges', 'free_delivery_amount', 'minimum_order_amount'],
components: {
},
data: function (){
return {
products: [],
calc: [],
}
},
methods : {
getCart(){
window.axios.get("/cart/get_cart").then(res => {
this.respond(res);
});
},
deleteCartItem(id){
window.axios.get("/cart/delete_cart_item/"+id).then(res => {
this.respond(res);
});
},
respond(res){
this.products = res.data.products;
this.calc = res.data.calc;
let elm = document.getElementById("myCart");
elm.innerHTML = this.products.length;
},
plus(product){
let q = product.data_cart + 1;
let qq = product.data_qty > this.buyqty ? this.buyqty : product.data_qty;
if(q <= qq) {
this.updateCart(product, q);
}
},
minus(product){
let q = product.data_cart - 1;
if(q <= 0) {
this.deleteCartItem(product.id);
} else {
this.updateCart(product, q);
}
},
updateCart(product, qty){
window.axios.post('/cart/add', {product_id:product.id, qty:qty}).then(res => {
this.getCart();
});
},
},
created(){
this.getCart();
},
mounted() {
},
}
</script>
|
<script>
import { IonMenu, IonHeader, IonToolbar, IonTitle, IonButton, IonList, IonItem, IonRouterOutlet, IonPage, IonButtons, IonMenuButton, IonIcon, IonSearchbar } from '@ionic/vue';
import { defineComponent } from 'vue';
import { useRouter } from 'vue-router';
import { chevronDown, chevronUp } from 'ionicons/icons';
import { mapActions, mapGetters } from 'vuex';
import {
IS_USER_AUTHENTICATE_GETTER,
LOGOUT_ACTION,
} from '../store/storeconstants';
export default defineComponent({
computed: {
showNavigation() {
return !['/login', '/signup'].includes(this.$route.path);
},
...mapGetters('auth', {
isAuthenticated: IS_USER_AUTHENTICATE_GETTER,
}),
activeItem() {
const trimmedPath = this.$route.path.replace(/\/$/, ''); // Trim the route path to remove any trailing slashes
return trimmedPath; // Use the trimmed path of the current route
}
},
methods: {
...mapActions('auth', {
logout: LOGOUT_ACTION,
}),
onLogout() {
this.logout();
this.$router.push('/login');
},
reloadPage(path) {
this.$router.push(path).then(() => {
window.location.reload();
});
},
toggleUserFormsDropdown() {
this.showUserForms = !this.showUserForms; // Toggle the visibility of the user forms dropdown
},
toggleUserPolicyDropdown() {
this.showUserPolicy = !this.showUserPolicy; // Toggle the visibility of the user policy dropdown
},
toggleAdminSettingsDropdown() {
this.showAdminSettings = !this.showAdminSettings; // Toggle the visibility of the admin settings dropdown
}
},
components: {
IonMenu,
IonHeader,
IonToolbar,
IonTitle,
IonButton,
IonList,
IonItem,
IonRouterOutlet,
IonPage,
IonButtons,
IonMenuButton,
IonIcon,
IonSearchbar
},
data() {
return {
chevronDown,
chevronUp,
showUserForms: false, // Initially hide the user forms dropdown
showUserPolicy: false, // Initially hide the user policy dropdown
showAdminSettings: false // Initially hide the admin settings dropdown
};
}
});
</script>
<template>
<ion-menu content-id="main-content">
<ion-header>
<ion-toolbar>
<img src="@/assets/bma.png" alt="BMA Logo" class="logo1" slot="start">
<ion-title class="title" slot="start"><strong>E-QMS</strong></ion-title>
</ion-toolbar>
</ion-header>
<ion-list class="SideList">
<!-- Show these items for admin role -->
<template v-if="$route.path.startsWith('/admin/')">
<ion-item @click="reloadPage('/admin/dashboard')" class="menu-item" :class="{ 'active-item': activeItem === '/admin/dashboard' }"> Dashboard </ion-item>
<ion-item @click="reloadPage('/admin/addPolicy')" class="menu-item" :class="{ 'active-item': activeItem === '/admin/addPolicy' }"> Policy Documents</ion-item>
<ion-item @click="reloadPage('/admin/addProcedures')" class="menu-item" :class="{ 'active-item': activeItem === '/admin/addProcedures' }"> Procedures </ion-item>
<ion-item @click="reloadPage('/admin/addWorkInstructions')" class="menu-item" :class="{ 'active-item': activeItem === '/admin/addWorkInstructions' }"> Work Instructions </ion-item>
<ion-item @click="reloadPage('/admin/addDepartments')" class="menu-item" :class="{ 'active-item': activeItem === '/admin/addDepartments' }"> Departments </ion-item>
<ion-item @click="reloadPage('/admin/addForm')" class="menu-item" :class="{ 'active-item': activeItem === '/admin/addForm' }"> Forms </ion-item>
<ion-item @click="reloadPage('/admin/addRecords')" class="menu-item" :class="{ 'active-item': activeItem === '/admin/addRecords' }"> Records </ion-item>
<ion-item @click="toggleAdminSettingsDropdown" class="menu-item" :class="{ 'active-item': activeItem === '/admin/settings' }">
Settings
<ion-icon slot="end" :icon="showAdminSettings ? chevronUp : chevronDown"></ion-icon>
</ion-item>
<ion-list v-show="showAdminSettings" class="subList">
<ion-item @click="reloadPage('/admin/accountManagement')" class="menu-item" :class="{ 'active-item': activeItem === '/admin/accountManagement' }">Account Management</ion-item>
<!-- Add other settings items here -->
</ion-list>
</template>
<!-- Show these items for user role -->
<template v-if="$route.path.startsWith('/user/')">
<ion-item @click="reloadPage('/user/dashboard')" class="menu-item" :class="{ 'active-item': activeItem === '/user/dashboard' }"> Dashboard </ion-item>
<ion-item @click="toggleUserPolicyDropdown" class="menu-item" :class="{ 'active-item': activeItem === '/user/policy' }">
Policy Documents
<ion-icon slot="end" :icon="showUserPolicy ? chevronUp : chevronDown"></ion-icon>
</ion-item>
<ion-list v-show="showUserPolicy" class="subList">
<ion-item @click="reloadPage('/user/generalPolicy')" class="menu-item" :class="{ 'active-item': activeItem === '/user/generalPolicy' }">General Policy</ion-item>
<ion-item @click="reloadPage('/user/departmentPolicy')" class="menu-item" :class="{ 'active-item': activeItem === '/user/departmentPolicy' }">Department Policy </ion-item>
</ion-list>
<ion-item @click="toggleUserFormsDropdown" class="menu-item" :class="{ 'active-item': activeItem === '/user/forms' }">
Forms
<ion-icon slot="end" :icon="showUserForms ? chevronUp : chevronDown"></ion-icon>
</ion-item>
<ion-list v-show="showUserForms" class="subList">
<ion-item @click="reloadPage('/user/generalForms')" class="menu-item" :class="{ 'active-item': activeItem === '/user/generalForms' }">General Forms</ion-item>
<ion-item @click="reloadPage('/user/departmentForms')" class="menu-item" :class="{ 'active-item': activeItem === '/user/departmentForms' }">Department Forms </ion-item>
</ion-list>
<!-- Add other user items similarly -->
</template>
</ion-list>
<ion-button @click="onLogout()" shape="round" class="btn logout" color="success" ><strong>Logout</strong></ion-button>
<!-- v-if="isAuthenticated for logout -->
</ion-menu>
<ion-page>
<ion-header v-if="showNavigation">
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<img src="@/assets/bma.png" alt="BMA Logo" class="logo2" slot="start">
<ion-title slot="start">
<strong>BALIWAG MARITIME ACADEMY</strong>
</ion-title>
<ion-searchbar class="search"></ion-searchbar>
<!-- Change title based on the route -->
<ion-title slot="end"><strong>{{ $route.path.startsWith('/user/') ? 'User' : 'Admin' }}</strong></ion-title>
<img src="@/assets/marine.png" alt="BMA Logo" class="logo3" slot="end" shape="round">
</ion-toolbar>
</ion-header>
<ion-router-outlet id="main-content"></ion-router-outlet>
</ion-page>
</template>
<style scoped>
.title {
text-align: center;
}
.SideList {
flex: 1;
margin-right: 12px;
margin-left: 10px;
}
.menu-item {
transition: all 0.3s ease-in-out;
color: black;
}
.menu-item:hover,
.menu-item.active-item {
font-weight: bold;
--background: #4caf50; /* Set the background color to green */
color: white;
}
.logout {
margin-right: 12px;
margin-left: 10px;
margin-bottom: 10px;
}
.subList {
width: 100%;
margin-left: 20px;
}
.logo1 {
width: 50px;
height: 50px;
margin: 5px;
margin-left: 50px;
margin-right: -20px;
}
.logo2 {
width: 50px;
height: 50px;
margin: 5px;
margin-right: -10px;
}
.logo3 {
width: 50px;
height: 50px;
margin-right: 15px;
}
</style>
|
package Games;
import Collidables.Block;
import Collidables.Collidable;
import Collidables.GameEnvironment;
import Collidables.Paddle;
import Geometry.Point;
import Geometry.Rectangle;
import Levels.LevelInformation;
import Listeners.ScoreTrackingListener;
import Listeners.VoidListener;
import Listeners.Counter;
import Listeners.BlockRemover;
import Listeners.BallRemover;
import Listeners.HitListener;
import Sprites.Sprite;
import Sprites.SpriteCollection;
import Sprites.Ball;
import Sprites.ScoreIndicator;
import biuoop.DrawSurface;
import biuoop.GUI;
import biuoop.KeyboardSensor;
import java.awt.Color;
/**
* The GameLevel class represents the game itself, initializing the objects and keeps the game going.
*
* @author Shlomo Shatz
*/
public class GameLevel implements Animation {
//The drawn ball's radius
public static final int DRAWN_RADIUS = 5;
//The starting point's X value;
public static final int STARTING_X = 400;
//The starting point's Y value;
public static final int STARTING_Y = 550 - 2 * DRAWN_RADIUS;
//Numbers defining the ratio of the gui
public static final int HEIGHT = 600;
public static final int WIDTH = 800;
//The thickness of the borders
public static final double BORDER_THICK = 25.0;
//The size of blocks being created
public static final int BLOCK_HEIGHT = 20;
//The score added to the winner
public static final int FINISHER_SCORE = 100;
//The collection of sprites
private SpriteCollection sprites;
//The environment of the game
private GameEnvironment environment;
//The GUI of the game
private GUI gui;
//The counter of blocks, balls and score
private Counter blockCounter;
private Counter ballCounter;
private Counter score;
private AnimationRunner runner;
private boolean running;
private KeyboardSensor keyboard;
/**
* The constructor of the class.
* @param gui The gui of the game
* @param runner The animation runner of the game
* @param keyboard The keyboard being pressed
* @param score The score counter of the user
*/
public GameLevel(GUI gui, AnimationRunner runner, KeyboardSensor keyboard, Counter score) {
this.gui = gui;
this.runner = runner;
this.keyboard = keyboard;
this.score = score;
}
/**
* Adds a collidable to the environment.
*
* @param c The collidable being added
*/
public void addCollidable(Collidable c) {
environment.addCollidable(c);
}
/**
* Adds a sprite to the sprite collection.
*
* @param s The sprite being added
*/
public void addSprite(Sprite s) {
sprites.addSprite(s);
}
/**
* Returns the GUI of the game.
*
* @return The GUI of the game
*/
public GUI getGui() {
return this.gui;
}
/**
* Initializes the game and creating the objects in it.
* @param currentLevel The current level
*/
public void initialize(LevelInformation currentLevel) {
//Initializes the sprite collection
sprites = new SpriteCollection();
//Initializes the environment
environment = new GameEnvironment();
//Creates the border blocks
VoidListener vl = new VoidListener();
sprites.addSprite(currentLevel.getBackground());
createBorderBlocks(vl, currentLevel);
//Creates the game blocks
createGameBlocks(currentLevel);
//Creates the paddle
createPaddle(vl, currentLevel);
}
/**
* Runs the game and keeps it going.
* @param level The current level
*/
public void run(LevelInformation level) {
this.runner.run(new CountdownAnimation(2, 3, this.sprites, level)); // countdown before turn starts.
this.running = true;
// use our runner to run the current animation -- which is one turn of
// the game.
this.runner.run(this);
}
/**
* Creates the balls with a random angle.
* @param currentLevel The current level
* @return The ball remover for the balls, used later in the program
*/
public BallRemover createBalls(LevelInformation currentLevel) {
//Initializes the counter for balls
this.ballCounter = new Counter(currentLevel.numberOfBalls());
//Creating a ball remover and updates its counter
BallRemover deathListener = new BallRemover(this);
deathListener.setRemainingBalls(this.ballCounter);
//Initializes the random instance
//Using a for loop to create balls based on the constant number
for (int i = 0; i < currentLevel.numberOfBalls(); i++) {
//Creates a ball at the starting point, at a specific radius and color
Ball ball = new Ball(STARTING_X, STARTING_Y, DRAWN_RADIUS, Color.RED);
ball.firstSetHitListeners();
ball.addHitListener(deathListener);
//Sets the velocity and environment of the ball
ball.setVelocity(currentLevel.initialBallVelocities().get(i));
ball.setEnvironment(environment);
//Adds the ball to the game
ball.addToGame(this);
}
return deathListener;
}
/**
* Creates the paddle of the game.
* @param hl The hit listener of the block
* @param currentLevel The current level
*/
public void createPaddle(HitListener hl, LevelInformation currentLevel) {
//Creates the paddle
Paddle paddle = new Paddle(new Block(new Rectangle(new Point(currentLevel.getPaddleStartX(),
currentLevel.getPaddleStartY()), currentLevel.paddleWidth(), BLOCK_HEIGHT, Color.ORANGE)),
currentLevel.paddleSpeed());
//Adds the paddle to the game
paddle.getBlock().firstSetHitListeners();
paddle.getBlock().addHitListener(hl);
paddle.addToGame(this);
}
/**
* Creates the border blocks.
* @param hl The hit listener of the blocks
* @param currentLevel The current level
*/
public void createBorderBlocks(HitListener hl, LevelInformation currentLevel) {
//Initializes the balls' hit listener
BallRemover deathListener = createBalls(currentLevel);
//Creates a block for the score display and adds it to the game
Block scoreBlock = new Block(new Rectangle(new Point(0, 0), WIDTH, BORDER_THICK, Color.WHITE));
scoreBlock.firstSetHitListeners();
scoreBlock.addHitListener(hl);
scoreBlock.addToGame(this);
//Creates the top block border
Block topBorder = new Block(new Rectangle(new Point(0, BORDER_THICK), WIDTH, BORDER_THICK, Color.GRAY));
//Adds it to the game
topBorder.firstSetHitListeners();
topBorder.addHitListener(hl);
topBorder.addToGame(this);
//Creates the left block border
Block leftBorder = new Block(new Rectangle(new Point(0, BORDER_THICK * 2),
BORDER_THICK, HEIGHT - (BORDER_THICK * 2), Color.GRAY));
//Adds it to the game
leftBorder.firstSetHitListeners();
leftBorder.addHitListener(hl);
leftBorder.addToGame(this);
//Creates the right block border
Block rightBorder = new Block(new Rectangle(new Point(WIDTH - BORDER_THICK, BORDER_THICK * 2),
BORDER_THICK, HEIGHT - BORDER_THICK * 2, Color.GRAY));
//Adds it to the game
rightBorder.firstSetHitListeners();
rightBorder.addHitListener(hl);
rightBorder.addToGame(this);
//Creates the lower block border
Block lowerBorder = new Block(new Rectangle(new Point(BORDER_THICK, HEIGHT - BORDER_THICK / 2),
WIDTH - 2 * BORDER_THICK, BORDER_THICK / 2, Color.RED));
//Adds it to the game
lowerBorder.firstSetHitListeners();
lowerBorder.addHitListener(deathListener);
lowerBorder.addToGame(this);
}
/**
* Creates the gaming blocks.
* @param currentLevel The current level
*/
public void createGameBlocks(LevelInformation currentLevel) {
//Initializes a score tracker
ScoreTrackingListener scoreListener = createScoreTracker(currentLevel);
this.blockCounter = new Counter(currentLevel.numberOfBlocksToRemove());
BlockRemover br = new BlockRemover(this);
//Creates the blocks of the first line
for (Block b : currentLevel.blocks()) {
b.firstSetHitListeners();
b.addHitListener(br);
b.addHitListener(scoreListener);
//Adds the row to the game
b.addToGame(this);
}
//Updates the listener's counter
br.setRemainingBlocks(this.blockCounter);
}
/**
* Creates a score tracking listener.
* @param currentLevel The current level
* @return The created score tracker
*/
public ScoreTrackingListener createScoreTracker(LevelInformation currentLevel) {
//Creates the tracker and connects it to the game score
ScoreTrackingListener scl = new ScoreTrackingListener(this.score);
ScoreIndicator scr = new ScoreIndicator(this.score, currentLevel.levelName());
//Adds it to the game and returns it
scr.addToGame(this);
return scl;
}
/**
* Removes a collidable from the game.
* @param c The removed collidable
*/
public void removeCollidable(Collidable c) {
environment.removeCollidable(c);
}
/**
* Removes a sprite from the game.
* @param s The removed sprite
*/
public void removeSprite(Sprite s) {
sprites.removeSprite(s);
}
/**
* A getter for the block counter.
* @return The block counter
*/
public Counter getBlockCounter() {
return this.blockCounter;
}
/**
* A getter for the ball counter.
* @return The ball counter
*/
public Counter getBallCounter() {
return this.ballCounter;
}
@Override
public boolean shouldStop() {
return !this.running;
}
@Override
public void doOneFrame(DrawSurface d) {
//Draws all the sprites
this.sprites.drawAllOn(d);
//Checks if pause is needed
if (this.keyboard.isPressed("p")) {
KeyPressStoppableAnimation keypress = new KeyPressStoppableAnimation(gui.getKeyboardSensor(),
KeyboardSensor.SPACE_KEY, new PauseScreen(this.keyboard, this.sprites));
runner.run(keypress);
}
//Checks if there are no more balls, and the user lost
if (this.ballCounter.getValue() <= 0) {
this.sprites.drawAllOn(d);
this.sprites.notifyAllTimePassed();
this.running = false;
}
//Checks if there are no more blocks
if (this.blockCounter.getValue() <= 0) {
//Raises the score a final amount
score.increase(FINISHER_SCORE);
//Updates the scoreboard to show the final score
this.sprites.notifyAllTimePassed();
this.sprites.drawAllOn(d);
this.running = false;
}
//Tells all the sprites the time has passed
this.sprites.notifyAllTimePassed();
}
}
|
//
// RelationshipCaring2.swift
// MeteorStorm
//
// Created by Luigi Luca Coletta on 16/11/21.
//
import SwiftUI
struct RelationshipCaring2: View {
@Binding var rootIsActive : Bool
@Binding var isCompleted : Bool
@State private var name: String = ""
var body: some View {
VStack{
Spacer()
Text("Think of a person you interacted with today")
.font(.system(size: 34, weight: .regular, design: .default))
.foregroundColor(Color.primary)
.padding()
Text("Type down their name")
.multilineTextAlignment(.center)
.font(.system(size: 17, weight: .regular, design: .default))
.foregroundColor(Color(.systemGray))
TextField("Name:", text: $name) //gets the text
.disableAutocorrection(true)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 14)
.stroke(Color(.systemIndigo), lineWidth: 2)
)
.padding()
Spacer()
if name == ""
{
Text("Continue")
.padding(.vertical)
.frame( maxWidth: .infinity)
.foregroundColor(Color.white)
.background(Color(.systemIndigo)).cornerRadius(14)
.padding(.horizontal)
.opacity(0.5)
}
else {
NavigationLink(destination: RelationshipCaring3(rootIsActive: self.$rootIsActive, isCompleted: self.$isCompleted, name: self.$name)) {
Text("Continue")
.padding(.vertical)
.frame( maxWidth: .infinity)
.foregroundColor(Color.white)
.background(Color(.systemIndigo)).cornerRadius(14)
.padding(.horizontal)
}
.isDetailLink(false)
}
}//VStack
.navigationTitle("Relationship Caring")
.padding(.bottom)
.onTapGesture{
hideKeyboard()
}
.toolbar{
Button{
self.rootIsActive = false } label: {
Text("Close")
.foregroundColor(Color(.systemIndigo))
}
}//Toolbar
}
}
struct RelationshipCaring2_Previews: PreviewProvider {
static var previews: some View {
RelationshipCaring2(rootIsActive: .constant(true), isCompleted: .constant(true))
}
}
|
<?php
namespace App\Entity;
use App\Repository\PersonneRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity(repositoryClass: PersonneRepository::class)]
class Personne
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string', length: 255)]
private ?string $nom;
#[ORM\Column(type: 'string', length: 255)]
private ?string $prenom;
#[Assert\GreaterThan('-150 years')]
#[ORM\Column(type: 'date')]
private ?\DateTimeInterface $dateDeNaissance;
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getDateDeNaissance(): ?\DateTimeInterface
{
return $this->dateDeNaissance;
}
public function setDateDeNaissance(\DateTimeInterface $dateDeNaissance): self
{
$this->dateDeNaissance = $dateDeNaissance;
return $this;
}
public function getAge(): int
{
$dateInterval = $this->dateDeNaissance->diff(new \DateTime());
return $dateInterval->y;
}
}
|
$(document).ready(function () {
// MODAL
var modalText = {
omniverse: {
title: "NVIDIA Omniverse Kondux Web3 Extension",
tag: "NVIDIA OMNIVERSE WEB3 EXTENSTION.",
detail:
"A unique webpage for a Texas drone business. Developed completely from ground up.",
link: "https://www.kondux.io",
codeLink: "Private Repo",
},
dApp: {
title: "Kondux Web3 dApp",
tag: "KONDUX WEB3 DAPP.",
detail:
"A decentralized web3 application that helps creators use their 3D assets collaboratively while having true ownership of their digital assets.",
link: "https://www.kondux.io/viewport",
codeLink: "Private Repo",
},
tdi: {
title: "Texas Drone Imaging",
tag: "TDI WEBSITE.",
detail:
"A unique webpage for a Texas drone business. Developed completely from ground up.",
link: "https://texasdroneimaging.net/",
codeLink: "https://github.com/Wsoukkachang/TDI",
},
seentence: {
title: "Seen-tence",
tag: "VISUAL LEARNING TOOL.",
detail:
"A visual learning tool to help people understand what they are reading faster. - You can actually hear and see your sentences! WIP - hosted on Firebase.",
link: "https://seentence2.web.app/",
codeLink: "https://github.com/Wsoukkachang/Seentence",
},
covid19: {
title: "Covid 19 Tracker",
tag: "COVID 19 TRACKER.",
detail:
"Covid-19 tracker app -- that displays a map, graph, and line chart with the most up-to-date statistics for Covid-19 cases.",
link: "https://covid19tracker-5585e.web.app",
codeLink: "https://github.com/Wsoukkachang/covid19tracker",
},
incog: {
title: "InCog",
tag: "ANONYMOUS FEEDBACK APPLICATION.",
detail:
"App that allows users to give anonymous, constructive feedback to their colleagues.",
link: "https://speakincog.com/landing",
codeLink: "https://github.com/anonymous-team-feedback",
},
sonic: {
title: "Sonic The Lambdog",
tag: "TRAVERSAL GAME APPLICATION.",
detail:
"A game app where players can traverse a 100+ room maze and interact with other players in real time.",
link: "https://zealous-poincare-b92bd3.netlify.app/",
codeLink: "https://github.com/Sonic-BW",
},
droom: {
title: "Droom",
tag: "JOB SEEKER APPLICATION.",
detail: "Think Tinder + LinkedIn.",
link: "https://dreamindroom.netlify.app/",
codeLink: "https://github.com/droom2019",
},
card: {
title: "Super Six Card Game",
tag: "MULITPLAYER CARD GAME.",
detail: "A strategic multiplayer card game.",
},
space: {
title: "Space Jumper",
tag: "ONLINE INTERACTIVE GAME.",
detail: "Simple, yet addicting game.",
link: "https://www.newgrounds.com/portal/view/641062",
},
greys: {
title: "The Greys",
tag: "ONLINE INTERACTIVE GAME.",
detail: " Play as The Greys and save as many humans as you can.",
link: "hhttps://www.newgrounds.com/portal/view/640824",
},
shapes: {
title: "Ancient Shapes",
tag: "SHAPE BUILDING INTERACTIVE GAME.",
detail:
"Construct barriers and create weapons to save yourself from alien forces.",
link: "https://www.newgrounds.com/portal/view/640245",
},
kratos: {
title: "Kratos Electrical Contractor LLC",
tag: "KRATOS ELECTRICAL CONTRACTOR LLC WEBSITE.",
detail:
"A unique webpage for a Texas electrical business. Developed completely from ground up.",
link: "https://kratoselectrical.com/",
},
};
$("#gallery .button").on("click", function () {
fillModal(this.id);
$(".modal-wrap").addClass("visible");
});
$(".close").on("click", function () {
$(".modal-wrap, #modal .button").removeClass("visible");
});
$(".mask").on("click", function () {
$(".modal-wrap, #modal .button").removeClass("visible");
});
var carousel = $("#carousel"),
slideWidth = 700,
threshold = slideWidth / 3,
dragStart,
dragEnd;
setDimensions();
$("#next").click(function () {
shiftSlide(-1);
});
$("#prev").click(function () {
shiftSlide(1);
});
carousel.on("mousedown", function () {
if (carousel.hasClass("transition")) return;
dragStart = event.pageX;
$(this).on("mousemove", function () {
dragEnd = event.pageX;
$(this).css("transform", "translateX(" + dragPos() + "px)");
});
$(document).on("mouseup", function () {
if (dragPos() > threshold) {
return shiftSlide(1);
}
if (dragPos() < -threshold) {
return shiftSlide(-1);
}
shiftSlide(0);
});
});
function setDimensions() {
if (
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
)
) {
slideWidth = $(window).innerWidth();
}
$(".carousel-wrap, .slide").css("width", slideWidth);
$(".modal").css("max-width", slideWidth);
$("#carousel").css("left", slideWidth * -1);
}
function dragPos() {
return dragEnd - dragStart;
}
function shiftSlide(direction) {
if (carousel.hasClass("transition")) return;
dragEnd = dragStart;
$(document).off("mouseup");
carousel
.off("mousemove")
.addClass("transition")
.css("transform", "translateX(" + direction * slideWidth + "px)");
setTimeout(function () {
if (direction === 1) {
$(".slide:first").before($(".slide:last"));
} else if (direction === -1) {
$(".slide:last").after($(".slide:first"));
}
carousel.removeClass("transition");
carousel.css("transform", "translateX(0px)");
}, 700);
}
function fillModal(id) {
$("#modal .title").text(modalText[id].title);
$("#modal .detail").text(modalText[id].detail);
$("#modal .tag").text(modalText[id].tag);
if (modalText[id].link)
$("#modal .button")
.addClass("visible")
.parent()
.attr("href", modalText[id].link);
if (modalText[id].codeLink)
$("#modal .buttonCode")
.addClass("visible")
.parent()
.attr("href", modalText[id].codeLink);
$.each($("#modal li"), function (index, value) {
$(this).text(modalText[id].bullets[index]);
});
$.each($("#modal .slide"), function (index, value) {
$(this).css({
background:
"url('img/slides/" + id + "-" + index + ".jpg') center center/cover",
backgroundSize: "cover",
});
});
}
});
|
import { Button } from "@material-tailwind/react";
import big_logo from "../components/Assets/logo_big.png";
import cart_icon from "../components/Assets/cart_icon.png";
import { Link, useLocation } from "react-router-dom";
import whatsappIcon from './Assets/whatsapp_icon.png'
import instagramIcon from './Assets/instagram_icon.png'
import pinterestIcon from './Assets/pintester_icon.png'
export default function Footer() {
const path = useLocation()
return (
<footer className={`w-full py-2 border-b shadow-sm mt-12 pt-6 ${path.pathname == '/login' ? 'hidden' : 'null'}`}>
<div className="md:container mx-auto lg:px-10 px-[15px] ">
<div className="flex flex-col gap-6 items-center mb-8">
<Link to='/' className="flex items-center gap-2">
<img className="w-12 md:w-14" src={big_logo} alt="big logo" />
<h1 className="uppercase text-2xl md:text-3xl font-semibold md:font-medium">Shopper</h1>
</Link>
{/* category */}
<ul className="flex gap-6 font-medium">
<li>
<Link to="#">
Company
</Link>
</li>
<li>
<Link to="#">
Products
</Link>
</li>
<li>
<Link to="#">
Offices
</Link>
</li>
<li>
<Link to="#">
About
</Link>
</li>
<li>
<Link to="#">
Contact
</Link>
</li>
</ul>
{/* cart login */}
<div className="flex gap-8 items-center select-none">
<Link to="#">
<img className="w-6 h-6" src={instagramIcon} alt="insta" />
</Link>
<Link to="#" className="relative active:bg-blue-gray-50">
<img className="w-6 h-6" src={pinterestIcon} alt="pinterest" />
</Link>
<Link to="#" className="relative active:bg-blue-gray-50">
<img className="w-6 h-6" src={whatsappIcon} alt="watsapp" />
</Link>
</div>
</div>
<div className="py-4 border-t-2 border-gray-700 mb-4">
<h2 className="font-semibold text-center text-gray-700">Copyrights @2024 - All rights reserved.</h2>
</div>
</div>
</footer>
)
}
|
import { Options, documentToReactComponents } from '@contentful/rich-text-react-renderer';
import { BLOCKS, Document } from '@contentful/rich-text-types';
import { Table, TableBody, TableCell, TableRow, Typography } from '@mui/material';
type RichText = (string | false | JSX.Element)[];
export const renderPriceTab = (data: Document) => {
const options: Options = {
renderNode: {
[BLOCKS.PARAGRAPH]: (node, children) => <Typography>{children}</Typography>,
[BLOCKS.TABLE]: (node, children) => (
<Table>
<colgroup>
<col width="25%" />
<col width="55%" />
<col width="auto" />
</colgroup>
<TableBody>{children}</TableBody>
</Table>
),
[BLOCKS.TABLE_ROW]: (node, children) => <TableRow>{children}</TableRow>,
[BLOCKS.TABLE_HEADER_CELL]: (node, children) => <TableCell>{children}</TableCell>,
[BLOCKS.TABLE_CELL]: (node, children) => <TableCell>{children}</TableCell>,
},
renderText: (text) => {
return text.split('\n').reduce((children: RichText, textSegment: string, index: number) => {
// eslint-disable-next-line react/no-array-index-key
return [...children, index > 0 && <br key={index} />, textSegment];
}, []);
},
};
return documentToReactComponents(data, options);
};
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import {
HttpClientModule
} from '@angular/common/http';
import {
HttpClientTestingModule,
HttpTestingController
} from '@angular/common/http/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AuthService } from './../../../auth/auth.service';
import { ApiService } from './../../../core/api.service';
import { UtilsService } from './../../../core/utils.service';
import { Service } from '../../../core/models/service';
import { ServiceDetailComponent } from './service-detail.component';
describe('ServiceDetailComponent', () => {
let component: ServiceDetailComponent;
let fixture: ComponentFixture<ServiceDetailComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ServiceDetailComponent ],
imports: [
FormsModule,
ReactiveFormsModule,
HttpClientModule,
HttpClientTestingModule,
RouterTestingModule
],
providers: [AuthService, ApiService, UtilsService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ServiceDetailComponent);
component = fixture.componentInstance;
component.service = new Service('New Service Title', 'New Service Description', 'New Service Image Path', []);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
module twitter
import mobl
external type Update {
@doc "The internal twitter ID"
id : Num
created_at : DateTime
text : String
source : String
in_reply_to_status_id : Num
in_reply_to_user_id : Num
favorited : Bool
user : User
}
external type User {
screen_name : String
name : String
location : String
url : String
profile_image_url : String
}
external type SearchResult {
created_at : DateTime
from_user : String
text : String
source : String
profile_image_url : String
}
external sync function getUpdates(username : String, password : String) : Collection<Update>
external sync function getMentions(username : String, password : String) : Collection<Update>
external sync function search(phrase : String) : Collection<SearchResult>
external function postUpdate(username : String, password : String, text : String) : Bool
external function postReply(username : String, password : String, replyToId : Num, text : String) : Bool
<script>
twitter.getUpdates = function(username, password, optionalArgs) {
return {
addEventListener: function() {},
list: function(_, callback) {
$.ajax({
url: mobl.proxyUrl('http://api.twitter.com/1/statuses/home_timeline.json', username, password),
datatype: "json",
error: function(_, message, error) {
console.log(message);
console.log(error);
callback([]);
},
success: function(data) {
var results = [];
var update;
for(var i = 0; i < data.length; i++) {
update = data[i];
update.created_at = Date.parse(update.created_at);
results.push(update);
}
callback(results);
}
});
}
};
};
twitter.getMentions = function(username, password, optionalArgs) {
return {
addEventListener: function() {},
list: function(_, callback) {
$.ajax({
url: mobl.proxyUrl('http://api.twitter.com/1/statuses/mentions.json', username, password),
datatype: "json",
error: function(_, message, error) {
console.log(message);
console.log(error);
callback([]);
},
success: function(data) {
var results = [];
var update;
for(var i = 0; i < data.length; i++) {
update = data[i];
update.created_at = Date.parse(update.created_at);
results.push(update);
}
callback(results);
}
});
}
};
};
twitter.search = function(phrase, optionalArgs) {
return {
_limit: 10,
addEventListener: function() {},
limit: function(n) {
this._limit = n;
return this;
},
list: function(_, callback) {
if(!phrase) {
callback([]);
return;
}
$.ajax({
url: mobl.proxyUrl('http://search.twitter.com/search.json?q='+escape(phrase) + '&rpp=' + this._limit),
datatype: "json",
error: function(_, message, error) {
console.log(message);
console.log(error);
callback([]);
},
success: function(data) {
var results = [];
var update;
//console.log(data);
data = data['results'];
for(var i = 0; i < data.length; i++) {
update = data[i];
update.created_at = Date.parse(update.created_at);
results.push(update);
}
callback(results);
}
});
}
};
};
twitter.postUpdate = function(username, password, text, optionalArgs, callback) {
$.ajax({
url: mobl.proxyUrl('http://api.twitter.com/1/statuses/update.json', username, password),
datatype: "json",
data: {status: text},
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Twitter-Client', 'zwitter');
},
error: function(_, message, error) {
console.log(message);
console.log(error);
callback(false);
},
success: function(data) {
callback(true);
}
});
};
twitter.postReply = function(username, password, replyToId, text, optionalArgs, callback) {
$.ajax({
url: mobl.proxyUrl('http://api.twitter.com/1/statuses/update.json', username, password),
datatype: "json",
data: {status: text, in_reply_to_status_id: replyToId},
type: 'POST',
error: function(_, message, error) {
console.log(message);
console.log(error);
callback(false);
},
success: function(data) {
callback(true);
}
});
};
</script>
|
# Welcome Fullstack Product Exercise
```
TIMEBOX: 4 hours max. We mean it!
LANGUAGES: Javascript
FRAMEWORKS: Any libraries you want
```
# Overview
This exercise is to implement the best possible solution to the exercises below in the time alloted. We're evaluating your ability to take a set of requirements and spike a holistic solution that demonstrates craftsmanship, thoughtfulness and attention to user experience. This is **NOT** a test of how well you know a specific framework or ES7+, nor should you try to impress us with overly clever and obtuse solutions or designs. If you want to impress us, build something that is beautiful, intuitive and easy to debug/test/extend :wink: .
Ideally your solution would have some way to run locally and visualize the results in a browser so we can fully analyze the experience and not just the source code.
## Search Airline Offers
### As a user I want to
* Enter shipment details in a form:
* Origin airport code in the 3-letter format (example: CAI, LAX, MAD)
* Destination airport in 3-letter format (example: CAI, LAX, MAD)
* Range of dates (up to 10 days)
* Weight of the shipment
* Display a list of the offers meeting the search criteria
* **NOTE**: You don't need to create an API to get a list of offers. Use the sample files in [/data](https://github.com/cargo-one/hiring-exercise/blob/main/data) or create your own simple faked data set.
* **stretch goal**: be able to filter or search by any unique identifiers so I can find specific offers.
* Share a link to my shipment's results via a unique URL
---------
# Submitting your exercise
1. See [instructions for submitting your work](https://github.com/cargo-one/hiring-exercise/blob/main/README.md#general-instructions)
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Add Book</title>
{% load static%}
<!-- BOOTSTRAP -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- LOCAL CSS -->
<link rel="stylesheet" href="{% static 'review_app/css/add.css' %}">
<script>
$(document).ready(function(){
$('input').focus(function(){
$(this).parent().find(".label-txt").addClass('label-active');
});
$("input").focusout(function(){
if ($(this).val() == '') {
$(this).parent().find(".label-txt").removeClass('label-active');
};
});
});
</script>
</head>
<body>
<div class="container" style="padding-top:30px">
<div class="top_bar">
<h1>Review App</h1>
<button type="submit" onclick="window.location.href='/dashboard'" class="goback"> Dashboard </button>
<h3> Welcome, {{pk.first_name}} </h3>
<form action="/logoff" method="POST" class="topform">
{% csrf_token %}
<button>Logout</button>
</form>
</div>
</div>
<div id="survey">
<form action="/validate_add_book" method="POST">
<h2>Add a new book</h2>
{% csrf_token %}
<label>
<p class="label-txt">Title</p>
<input type="text" class="input" name="title">
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">Author</p>
<input type="text" class="input" name="author">
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">Review</p>
<input type="text" class="input" name="review">
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">Rating</p>
<input type="text" class="input" name="rating">
<div class="line-box">
<div class="line"></div>
</div>
</label>
<button type="submit" class="create">Add</button>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</form>
</div>
</body>
</html>
|
import { createReducer, on } from '@ngrx/store';
import { Category } from '@models/index';
import { categoriesLoaded, loadCategories } from '../menu.actions';
import { createEntityAdapter, EntityState } from '@ngrx/entity';
export const menuFeatureKey = 'menu';
export interface MenuState extends EntityState<Category> {
categoriesLoaded: boolean;
isLoading: boolean;
}
export const adapter = createEntityAdapter<Category>({
selectId: (category: Category) => category._id,
});
export const initialMenuState = adapter.getInitialState({
categoriesLoaded: false,
isLoading: false,
});
export const menuReducer = createReducer(
initialMenuState,
on(loadCategories, (state): MenuState => ({ ...state, isLoading: true })),
on(categoriesLoaded, (state: MenuState, { categories }) =>
adapter.setAll(categories, {
...state,
isLoading: false,
categoriesLoaded: true,
})
)
);
export const { selectAll } = adapter.getSelectors();
|
import { JwtModule } from '@nestjs/jwt'
import { Test } from '@nestjs/testing'
import { UserRepository } from './user.repository'
import { AuthService } from './auth.service'
import { jwtConfig } from '../config'
import { User } from './user.entity'
import { CreateUserDto } from './dtos/create-user.dto'
import { UnauthorizedException } from '@nestjs/common'
const users: User[] = []
const mockAuthService = {
signup: jest.fn(() => Promise.resolve()),
signin: jest.fn(() => Promise.resolve({ accessToken: 'asdas' }))
}
const mockUserRepository: Partial<UserRepository> = {
signup: jest.fn((username: string, password: string) => {
const user = {
id: Math.floor(Math.random() * 999999),
username,
password,
created_at: new Date(),
updated_at: new Date()
} as User
users.push(user)
return Promise.resolve()
}),
findOneByUsername: jest.fn((username: string) => {
const user = users.find((user) => user.username === username)
return Promise.resolve(user)
})
}
describe('AuthService', () => {
let authService: AuthService
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [JwtModule.register(jwtConfig)],
providers: [
AuthService,
{
provide: UserRepository,
useValue: mockUserRepository
}
]
})
.overrideProvider(AuthService)
.useValue(mockAuthService)
.compile()
authService = await module.get(AuthService)
})
describe('signup()', () => {
it('Should call signup method', async () => {
const dto: CreateUserDto = { username: 'test', password: 'test' }
await authService.signup(dto)
expect(authService.signup).toHaveBeenCalledWith(dto)
await mockUserRepository.signup(dto.username, dto.password)
expect(mockUserRepository.signup).toHaveBeenCalledWith(dto.username, dto.password)
})
})
describe('signin()', () => {
it('Should call signin method', async () => {
const dto: CreateUserDto = { username: 'test', password: 'test' }
await authService.signin(dto)
expect(authService.signin).toHaveBeenCalledWith(dto)
await mockUserRepository.findOneByUsername(dto.username)
expect(mockUserRepository.findOneByUsername).toHaveBeenCalledWith(dto.username)
expect(await mockAuthService.signin()).toEqual({ accessToken: expect.any(String) })
})
it('Throw if an invalid password is provided', async () => {
try {
const dto: CreateUserDto = { username: 'test', password: 'test1' }
const user = await mockUserRepository.findOneByUsername(dto.username)
expect(mockUserRepository.findOneByUsername).toHaveBeenCalledWith(dto.username)
user.validateUserPassword = jest.fn(() => Promise.resolve(false))
await user.validateUserPassword(dto.password)
expect(user.validateUserPassword).toHaveBeenCalledWith(dto.password)
expect(user.validateUserPassword(dto.password)).resolves.toBeFalsy()
} catch (error) {
expect(error).toBeInstanceOf(UnauthorizedException)
}
})
it('Throw if user not found', async () => {
try {
const dto: CreateUserDto = { username: 'test1', password: 'test' }
const user = await mockUserRepository.findOneByUsername(dto.username)
expect(mockUserRepository.findOneByUsername).toHaveBeenCalledWith(dto.username)
expect(user).toBeUndefined()
} catch (error) {
expect(error).toBeInstanceOf(UnauthorizedException)
}
})
})
})
|
import { useEffect, useRef } from "react";
import { priceToString } from "../../../../../utils";
function PriceModal({
showModal,
setShowModal,
price,
setPrice,
setFilterPrice,
}) {
const modalRef = useRef();
const buttonRef = useRef();
const closeModal = () => {
setFilterPrice(price);
setShowModal(false);
};
const modalOutSideClick = (e) => {
if (modalRef.current === e.target) closeModal();
};
const handleKeyPress = (event) => {
if (event.key === "Escape") setShowModal(false);
else if (event.key === "Enter") buttonRef.current.click();
};
useEffect(() => {
if (!showModal) return document.body.classList.remove("overflow-hidden");
document.body.classList.add("overflow-hidden");
document.addEventListener("keydown", handleKeyPress);
return () => {
document.removeEventListener("keydown", handleKeyPress);
};
}, [showModal]);
return (
<div
className={`modal-container fixed top-0 left-0 z-50 w-screen h-screen bg-darkgray bg-opacity-50 scale-100 flex ${
showModal ? "active" : ""
}`}
ref={modalRef}
onClick={(e) => modalOutSideClick(e)}
>
<div className="m-auto shadow w-96 rounded-xl">
<div className="flex flex-col gap-10 justify-center h-64 text-center bg-white rounded-t-xl">
<div className="text-xl text-black">1인당 가격범위 설정</div>
<div className="px-12">
<div className="w-full h-6 relative flex items-center mb-1.5">
<div className="w-full h-2 rounded-full bg-[#d9d9d9] relative">
<div
className="h-2 rounded-full bg-primary absolute top-0 left-0"
style={{ width: `${price / 10100}%` }}
/>
</div>
<input
className="absolute w-full h-6 bg-transparent slider z-20 top-0 left-0 focus:outline-none"
type="range"
min={0}
max={1010000}
step={10000}
name="price"
value={price}
onChange={(e) => setPrice(e.target.value)}
/>
</div>
</div>
<div className="text-xl text-primary">{`최고 금액: ${
price > 1000000 ? "상관없이" : priceToString(price) + "원"
}`}</div>
</div>
<button
className="w-full h-16 text-lg text-center text-white rounded-b-xl bg-primary"
onClick={closeModal}
ref={buttonRef}
>
확인
</button>
</div>
</div>
);
}
export default PriceModal;
|
import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import useFetch from "../hooks/useFetch";
function Login(props) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const users = useFetch("http://localhost:7000/users", []);
const [error, setError] = useState("");
const navigate = useNavigate();
function handleUserameChange(e) {
setError("");
setUsername(e.target.value);
}
function handlePasswordChange(e) {
setError("");
setPassword(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
users.forEach((u) => {
if (u.username === username && u.password === password) {
localStorage.setItem("signedInUser", u.id);
setUsername("");
setPassword("");
props.changeSignedIn();
navigate(`/`);
} else {
setError("Username or password not correct");
}
});
}
return (
<div className="view-frame white-bg text-center">
<h1>Login</h1>
<form onSubmit={handleSubmit} className="block-container">
<label htmlFor="username-input">Användarnamn: </label>
<input
onChange={handleUserameChange}
className="input-field"
id="username-input"
type="text"
placeholder="Användarnamn"
value={username}
required
/>
<label htmlFor="password-input">Lösenord: </label>
<input
onChange={handlePasswordChange}
className="input-field"
id="password-input"
type="password"
placeholder="Lösenord"
value={password}
required
/>
<div>
<p className="text-warning">{error}</p>
<button type="submit" className="green-btn">
Logga in
</button>
<Link to="/register">
<button className="green-btn">Registrera</button>
</Link>
</div>
</form>
</div>
);
}
export default Login;
|
from controller import Robot
import numpy as np
import csv
import math
import matplotlib.pyplot as plt
# for communication over files
import socket
import json
#to automatically start the visualization
import subprocess
import os
import signal
# Start the visualization script
visualization_process = subprocess.Popen(['python3', 'visualize_signals.py'])
# Function to generate step signal
def step_signal(t, step_time, initial_value, final_value):
return initial_value if t < step_time else final_value
plt.clf()
# Initialize the Robot
robot = Robot()
# Get the time step of the current world.
timestep = int(robot.getBasicTimeStep())
accel=robot.getDevice('accel')
accel.enable(timestep)
#Function for getting tilt angle from the Accelerometer Data
def getAngle(accelValues):
accelX=accelValues[0]
accelY=accelValues[1]
accelZ=accelValues[2]
angleParameter=accelY/math.sqrt(accelX**2+accelZ**2)
angle=math.atan(angleParameter)
angleDegrees=math.degrees(angle)
return angleDegrees
# Define motor objects
left_motor = robot.getDevice('left_wheel')
right_motor = robot.getDevice('right_wheel')
left_motor.setPosition(float('inf'))
right_motor.setPosition(float('inf'))
# Set initial velocity to 0
left_motor.setVelocity(0.0)
right_motor.setVelocity(0.0)
# Signal parameters
step_time = 1.0 # seconds
initial_value = 0.0 # rad/s
final_value = 2.0 # rad/s
# Set up socket communication
server_address = ('localhost', 65432)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Functions for robot movement
def moveForward(speed):
left_motor.setVelocity(speed)
right_motor.setVelocity(speed)
def moveBackward(speed):
left_motor.setVelocity(-speed)
right_motor.setVelocity(-speed)
def stop():
left_motor.setVelocity(0)
right_motor.setVelocity(0)
p=0.4
error=0
try:
start_time = robot.getTime()
while robot.step(timestep) != -1:
current_time = robot.getTime() - start_time
accelValues=accel.getValues()
# print(accelValues)
angle=getAngle(accelValues)
# print(angle)
# Generate step signal for velocity
# velocity = step_signal(current_time, step_time, initial_value, final_value)
# Apply velocity to motors
# left_motor.setVelocity(velocity)
# right_motor.setVelocity(velocity)
#Motor
speed=p*error
#controller
if angle>2:
error=angle
speed=p*error
moveForward(speed)
elif angle<-2:
error=angle
speed=p*error
moveForward(speed)
else:
error=0
stop()
# Get robot position
# left_position = left_motor.getTargetPosition()
# right_position = right_motor.getTargetPosition()
# Prepare data for sending
data = {
'time': current_time,
'velocity': speed,
'tilt_angle': angle
}
# Send data
sock.sendto(json.dumps(data).encode(), server_address)
if current_time > step_time + 5: # Run the simulation for a total of 15 seconds
break
finally:
# Terminate the visualization process when the simulation ends or is interrupted
visualization_process.terminate()
sock.close()
|
'use client'
import { mapState } from "@/atom";
import { useState } from "react";
import { MdOutlineMyLocation } from "react-icons/md";
import { useRecoilValue } from "recoil";
import { toast } from "react-toastify";
import FullPageLoader from "../FullpageLoader";
export default function CurrentLocationButton() {
const [loading, setLoading] = useState<boolean>(false);
const map = useRecoilValue(mapState);
const handleCurrentPosition = () => {
setLoading(true);
//geolocation 으로 현재 위치 가져오기
const options = {
// ture로 하면 정확한 값을 가져오지만 너무 느려짐
enableHighAccuracy: false,
timeout: 5000,
// 값을 Infinity 주면 항상 캐시가 되서 굉장히 빠르게 작동을 하고
// 그게 아닌 경우에는 항상 누를 때 마다 캐시되지 않은 위치를 가져오는 거 같음
maximumAge: Infinity,
};
if(navigator.geolocation && map) {
navigator.geolocation.getCurrentPosition(
// 성공케이스
(position) => {
const currentPosition = new window.kakao.maps.LatLng(
position.coords.latitude,
position.coords.longitude
);
// console.log(getCurrentPosition)
if(currentPosition) {
setLoading(false)
map.panTo(currentPosition);
toast.success("현재 위치로 이동되었습니다.")
}
return currentPosition;
},
// 에러가 났을 경우에
() => {
toast.error("현재 위치를 가져올 수 없습니다.")
setLoading(false);
},
options
)
}
};
return (
<>
{loading && <FullPageLoader />}
<button
type="button"
onClick={handleCurrentPosition}
className="fixed z-10 p-2 shadow right-10 bottom-20 bg-white rounded-md hover:shadow-lg focus:shadow-lg hover:bg-blue-200"
>
<MdOutlineMyLocation className="w-5 h-5"/>
</button>
</>
)
}
|
#![feature(let_chains)]
use std::fmt::Debug;
use rspack_error::Error;
use swc_core::ecma::ast::Regex as SwcRegex;
use self::algo::Algo;
mod algo;
/// Using wrapper type required by [TryFrom] trait
#[derive(Clone, Hash)]
pub struct RspackRegex {
pub algo: Algo,
raw: String,
}
impl Debug for RspackRegex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("RspackRegex").field(&self.raw).finish()
}
}
impl RspackRegex {
pub fn test(&self, text: &str) -> bool {
self.algo.test(text)
}
pub fn global(&self) -> bool {
self.algo.global()
}
pub fn sticky(&self) -> bool {
self.algo.sticky()
}
pub fn with_flags(expr: &str, flags: &str) -> Result<Self, Error> {
let mut chars = flags.chars().collect::<Vec<char>>();
chars.sort();
let raw = format!("{expr}|{}", chars.into_iter().collect::<String>());
Ok(Self {
raw,
algo: Algo::new(expr, flags)?,
})
}
pub fn new(expr: &str) -> Result<Self, Error> {
Self::with_flags(expr, "")
}
}
impl TryFrom<&SwcRegex> for RspackRegex {
type Error = Error;
fn try_from(value: &SwcRegex) -> Result<Self, Self::Error> {
RspackRegex::with_flags(value.exp.as_ref(), value.flags.as_ref())
}
}
impl TryFrom<SwcRegex> for RspackRegex {
type Error = Error;
fn try_from(value: SwcRegex) -> Result<Self, Self::Error> {
RspackRegex::with_flags(value.exp.as_ref(), value.flags.as_ref())
}
}
pub fn regexp_as_str(reg: &RspackRegex) -> &str {
®.raw
}
|
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import Sidebar from './components/Sidebar';
import GymInfo from "./components/Gyminfo";
import React, {useState, useEffect} from "react";
import "./style.css";
import Map from "./components/Map";
import { NavigationContainer } from '@react-navigation/native';
import {
createDrawerNavigator,
DrawerContentScrollView,
DrawerItemList,
DrawerItem,
} from '@react-navigation/drawer';
export default function App() {
return (
<NavigationContainer>
<MyDrawer />
</NavigationContainer>
);
};
function renderGymCards(gyms) {
return gyms.map(gym => (
<GymInfo
key={gym.name}
name={gym.name}
address={gym.address}
activities={gym.activities}
/>
));
}
const gyms = [
{
name: "Fitness & Fuel",
address: "390 Western Ave, Brighton, MA",
activities: ["Strength Training", "Women's Personal Trainig", "Group Exercises"]
},
{
name: "Amplify Fitness",
address: "1230 Soldiers Field Road, Boston, MA",
activities: ["Kickboxing", "Personal Training", "Youth Classes", "Outdoor Classes"]
},
{
name: "Red City Fitness",
address: "1 Braintree St, Allston, MA",
activities: ["Group Class", "Boxing", "Personal Training", ]
},
{
name: "NB Fitness Club, LLC",
address: "40 Life St, Brighton, MA",
activities: ["Cycling", "Kickboxing", "Resistance Training"]
},
{
name: "GymIt",
address: "920 Commonwealth Ave, Boston, MA",
activities: ["Personal Training", "Resistance Training", "Strength Training"]
}
];
function Home({ navigation }) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<React.Fragment>
<Map />
{renderGymCards(gyms)}
</React.Fragment>
</View>
);
}
function Feed() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Feed</Text>
</View>
);
}
function Profile() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Profile </Text>
</View>
)
}
function ConnectWearable() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Connect Wearable </Text>
</View>
)
}
function Settings() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Settings </Text>
</View>
)
}
function CustomDrawerContent(props) {
return (
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
<DrawerItem
label="Sign Out"
onPress={() => props.navigation.closeDrawer()}
/>
</DrawerContentScrollView>
);
}
const Drawer = createDrawerNavigator();
function MyDrawer() {
return (
<Drawer.Navigator
useLegacyImplementation
drawerContent={(props) => <CustomDrawerContent {...props} />}
>
<Drawer.Screen name="Home" component={Home} />
<Drawer.Screen name="Feed" component={Feed} />
<Drawer.Screen name="Profile" component={Profile} />
<Drawer.Screen name="Connect Wearable" component={ConnectWearable} />
<Drawer.Screen name="Settings" component={Settings} />
</Drawer.Navigator>
);
}
export const getCurrentLocation = (simulator) => {
return async (dispatch) => {
if (!simulator) {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
dispatch(gotCurrentLocationError('Permission to access location was denied'))
}
let location = await Location.getCurrentPositionAsync({});
dispatch(gotCurrentLocation(location))
} else {
// Demo location for simulator
dispatch(gotCurrentLocation(chicagoFSA))
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export const HomeScreen = () => {
return (
<div className="home-screen">
<div className="overlap-group-wrapper">
<div className="overlap-group">
<div className="streamline-interface" />
<img className="screenshot" alt="Screenshot" src="screenshot-2023-10-21-121613-1.png" />
<img className="vector" alt="Vector" src="vector.svg" />
<p className="any-plans-for-the">
<span className="text-wrapper">Any plans for the day?</span>
<span className="span"> </span>
</p>
<img className="subway-up" alt="Subway up" src="subway-up-2.svg" />
<img className="ph-map-pin-fill" alt="Ph map pin fill" src="ph-map-pin-fill.svg" />
<img className="img" alt="Ph map pin fill" src="image.svg" />
</div>
</div>
</div>
);
};
|
"""
Generator that takes nz dimensional noise and generates 128 x 128 x 3 image
Ref: https://github.com/pytorch/examples/issues/70
sigmoid layer at the last maps the output image into floats [0, 1] that can me mapped to [0, 255]
"""
from torch import nn
import json
import torch
class Generator(nn.Module):
def __init__(self, config_file):
super(Generator, self).__init__()
config = json.load(open(config_file, "r"))
# size of latent code
nz = config["nz"]
self.nz = nz
# size of feature maps in generator
ngf = config["ngf"]
# number of channels in training images
nc = config["nc"]
self.main = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d(nz, ngf * 16, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 16),
nn.ReLU(True),
# state size. (ngf*16) x 4 x 4
nn.ConvTranspose2d(ngf * 16, ngf * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 8),
nn.ReLU(True),
# state size. (ngf*8) x 8 x 8
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
# state size. (ngf*4) x 16 x 16
nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
# state size. (ngf*2) x 32 x 32
nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
# state size. (ngf) x 64 x 64
nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),
# Tanh takes it to [-1, 1]
# nn.Tanh()
# our textures are [0, 1] tensors
nn.Sigmoid()
# state size. (nc) x 128 x 128
)
def forward(self, inp):
return self.main(inp)
def generate_noise(self, batch_size):
return torch.randn(batch_size, self.nz, 1, 1)
|
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
class Vehicle {
private:
int id;
string name;
string type;
string brand;
string year;
string owner;
string check_date;
public:
Vehicle() {}
Vehicle(int id, string name, string type, string brand, string year, string owner) {
this->id = id;
this->name = name;
this->type = type;
this->brand = brand;
this->year = year;
this->owner = owner;
this->check_date = "05/2023";
}
bool needCheck(string a);
void display() {
cout << this->id << " " << this->name << " " << this->type << " " << this->brand << " " <<
this->year << " " << this->owner << endl;
}
friend ostream& operator << (ostream& out, Vehicle& xe);
Vehicle& operator += (int x) {
istringstream iss(year);
string s;
getline(iss, s, '/');
int m = stoi(s);
getline(iss, s, '/');
int y = stoi(s);
int mm = m + x;
while (mm > 12) {
mm -= 12;
y++;
}
string p = mm >= 10 ? to_string(mm) : ("0" + to_string(mm));
this->year = p + "/" + to_string(y);
return *this;
}
};
|
import UIKit
class Service {
var accessTokens: String? = ""
func fetchAnimals(currentPage: Int, _ completion: @escaping (AnimalsList?) -> Void) {
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
getTokens { token in
defer {
dispatchGroup.leave()
}
guard let token = token else {
completion(nil)
return
}
let urlString = URL(string: "https://api.petfinder.com/v2/animals")!
var request = URLRequest(url: urlString)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, _, error in
if let _ = error {
completion(nil)
return
}
if let data = data {
let jsonDecodable = JSONDecoder()
jsonDecodable.keyDecodingStrategy = .convertFromSnakeCase
do {
let animals = try jsonDecodable.decode(AnimalsList.self, from: data)
print("&& sucesso: \(animals)")
completion(animals)
} catch {
print("&& erro: \(error)")
completion(nil)
}
}
}
task.resume()
}
dispatchGroup.wait()
}
func getTokens(completion: @escaping (String?) -> Void) {
let tokenURL = URL(string: "https://api.petfinder.com/v2/oauth2/token")!
let clientId: String = "jzReeSDZAktQCYJrIcq0Rti0I60q9OxK6MexktPsr4SISLUWGy"
let clientSecret: String = "JkjlU0t1EBfUtb70xN6JGa8E8gSARBPtd7Xj3pFq"
var body = "grant_type=client_credentials"
body += "&client_id=\(clientId)"
body += "&client_secret=\(clientSecret)"
var request = URLRequest(url: tokenURL)
request.httpMethod = "POST"
request.httpBody = body.data(using: .utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { data, _, error in
guard let data = data, error == nil else {
print("Erro ao obter token:", error?.localizedDescription ?? "Erro desconhecido")
completion(nil)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
if let accessToken = json?["access_token"] as? String {
print("Sucesso ao obter token. Resposta:", accessToken)
completion(accessToken)
} else {
print("Erro ao obter token. Resposta:", json ?? "")
completion(nil)
}
} catch {
print("Erro ao processar dados JSON:", error.localizedDescription)
completion(nil)
}
}
task.resume()
}
}
|
import * as Separator from '@radix-ui/react-separator'
import { FacebookAuthProvider, GoogleAuthProvider } from 'firebase/auth'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { parseCookies } from 'nookies'
import { FacebookLogo, GoogleLogo, X } from 'phosphor-react'
import { FormEvent, useEffect, useState } from 'react'
import { Button } from '~/components/Atoms/Button'
import { InputLogin } from '~/components/Atoms/InputLogin'
import { Loading } from '~/components/Atoms/Loading'
import { Header } from '~/components/Molecules/Header'
import UseAuth from '~/hooks/useAuth'
export default function Login() {
const { signInWithProvider, loginWithEmailAndPassword, loading } = UseAuth()
const { token } = parseCookies()
const googleProvider = new GoogleAuthProvider()
const facebookProvider = new FacebookAuthProvider()
const router = useRouter()
const [email, setEmail] = useState<string>('')
const [password, setPassword] = useState<string>('')
useEffect(() => {
if (token !== '') {
router.push('/')
}
}, [token, router])
function loginUser(event: FormEvent) {
event.preventDefault()
loginWithEmailAndPassword(email, password)
}
return (
<>
<Header />
{loading ? (
<div className="w-full h-[80vh] relative my-auto">
<Loading />
</div>
) : (
<div className=" flex flex-col items-center mt-40 lg:h-[480px]">
<div className="bg-zinc-800 relative w-full py-8 px-5 lg:w-[634px] lg:rounded-lg lg:pt-16 lg:pb-9 lg:px-8">
<X size={24} className="absolute top-5 right-5 cursor-pointer" />
<div className="flex flex-col h-full">
<div className="flex h-full flex-col lg:flex-row">
<section className="w-full">
<h1 className="mt-5 mb-6 font-medium text-2xl text-zinc-100 lg:mb-5">
Entre com suas redes sociais
</h1>
<div>
<button
onClick={() => signInWithProvider(facebookProvider)}
className="w-full h-10 rounded-lg text-xs font-medium p-2 flex items-center bg-[#3b5998] hover:bg-[#8b9dc3] transition-colors justify-start mb-4"
>
<FacebookLogo size={24} weight="bold" className="mr-5" />
<p className="mr-15 font-medium flex-grow">
Entrar com Facebook
</p>
</button>
<button
className="w-full h-10 rounded-lg text-xs font-medium p-2 flex items-center bg-white hover:bg-slate-200 transition-colors justify-start mb-4"
onClick={() => signInWithProvider(googleProvider)}
>
<GoogleLogo
size={24}
weight="bold"
className="mr-5 text-zinc-600"
/>
<p className="mr-15 font-medium flex-grow text-zinc-600">
Entrar com Google
</p>
</button>
</div>
</section>
<Separator.Root className="relative my-4 border border-solid border-zinc-700 lg:mx-8">
<p className="absolute left-1/2 top-[-12px] lg:top-1/2 lg:left-[-20px] bg-zinc-800 px-2">
OU
</p>
</Separator.Root>
<section className="w-full">
<h1 className="mt-5 mb-6 font-medium text-2xl text-zinc-100 lg:mb-5">
Digite sua senha e e-mail
</h1>
<form onSubmit={(event) => loginUser(event)}>
<InputLogin
text="E-mail"
onChange={(event) => setEmail(event.target.value)}
id="E-mail"
/>
<InputLogin
type="password"
text="Senha"
onChange={(event) => setPassword(event.target.value)}
id="Senha"
/>
<Button type="submit" lgwidth="lg:w-auto">
Entrar
</Button>
</form>
</section>
</div>
<p className="text-center text-zinc-100 mt-8">
Não tem uma conta?
<Link href="/cadastrar">
<a className="ml-1 font-bold text-brand-primary hover:text-brand-hover transition-colors">
Crie a sua
</a>
</Link>
</p>
</div>
</div>
</div>
)}
</>
)
}
|
import React from 'react';
import { IDirectoryModel, IItemModel, useApiEditorStorage } from 'tno-core';
import { useAjaxWrapper } from '..';
interface IStorageController {
directoryExists: (locationId: number, path?: string) => Promise<boolean>;
getDirectory: (locationId: number, path?: string) => Promise<IDirectoryModel>;
upload: (
locationId: number,
path: string,
file: File,
overwrite?: boolean,
onUploadProgress?: (progressEvent: any) => void,
) => Promise<IItemModel>;
download: (locationId: number, path: string) => Promise<unknown>;
stream: (locationId: number, path: string) => Promise<string>;
move: (locationId: number, path: string, destination: string) => Promise<IItemModel>;
delete: (locationId: number, path: string) => Promise<IItemModel>;
clip: (
locationId: number,
path: string,
start: string,
end: string,
outputName: string,
) => Promise<IItemModel>;
join: (locationId: number, path: string, prefix: string) => Promise<IItemModel>;
}
export const useStorage = (): IStorageController => {
const dispatch = useAjaxWrapper();
const api = useApiEditorStorage();
const controller = React.useMemo(
() => ({
directoryExists: async (locationId?: number, path?: string) => {
const response = await dispatch<string>('storage-folder-exists', () =>
api.directoryExists(locationId, path),
);
return response.status === 200;
},
getDirectory: async (locationId: number, path?: string) => {
return (
await dispatch<IDirectoryModel>('get-storage', () => api.getDirectory(locationId, path))
).data;
},
upload: async (
locationId: number,
path: string,
file: File,
overwrite?: boolean,
onUploadProgress?: (progressEvent: any) => void,
) => {
return (
await dispatch<IItemModel>('storage-upload', () =>
api.upload(locationId, path, file, overwrite, onUploadProgress),
)
).data;
},
download: async (locationId: number, path: string) => {
return (
await dispatch<IItemModel>('storage-download', () => api.download(locationId, path))
).data;
},
stream: async (locationId: number, path: string) => {
return (await dispatch<string>('storage-stream', () => api.stream(locationId, path))).data;
},
move: async (locationId: number, path: string, destination: string) => {
return (
await dispatch<IItemModel>('storage-move', () => api.move(locationId, path, destination))
).data;
},
delete: async (locationId: number, path: string) => {
return (await dispatch<IItemModel>('storage-delete', () => api.delete(locationId, path)))
.data;
},
clip: async (
locationId: number,
path: string,
start: string,
end: string,
outputName: string,
) => {
return (
await dispatch<IItemModel>('storage-clip', () =>
api.clip(locationId, path, start, end, outputName),
)
).data;
},
join: async (locationId: number, path: string, prefix: string) => {
return (
await dispatch<IItemModel>('storage-join', () => api.join(locationId, path, prefix))
).data;
},
}),
[dispatch, api],
);
return controller;
};
|
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import { Trash2 } from 'lucide-react';
import Swal from 'sweetalert2';
import { useAxios } from '../../../hooks/useAxios';
import { useCart } from '../../../hooks/useCart';
export default function CartTable({rows}) {
const axiosSecure = useAxios()
const { cartDataRefetch} = useCart()
const handleDeleteItem = (id) => {
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!"
}).then(async(result) => {
if (result.isConfirmed) {
const res = await axiosSecure.delete(`/cart/${id}`)
if(res.data.deletedCount > 0) {
cartDataRefetch()
Swal.fire({
title: "Deleted!",
text: "Your file has been deleted.",
icon: "success"
});
}
}
});
}
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead className='bg-primary '>
<TableRow className='text-white font-medium'>
<TableCell></TableCell>
<TableCell>ITEM IMAGE</TableCell>
<TableCell >ITEM NAME</TableCell>
<TableCell >PRICE</TableCell>
<TableCell >ACTION</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row) => (
<TableRow
key={row._id}
sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
>
<TableCell component="th" scope="row">
<div>1</div>
</TableCell>
<TableCell component="th" scope="row">
<img src={row.image} className='h-16 w-16 rounded-md'/>
</TableCell>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell >${row.price}</TableCell>
<TableCell >
<div onClick={() => handleDeleteItem(row._id)} className='px-2 py-3 rounded-sm bg-red-600 w-12 flex items-center justify-center text-white hover:opacity-75 transition cursor-pointer'>
<Trash2 size={18} />
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.