text
stringlengths 184
4.48M
|
---|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<main>
<section>
<!--La etiqueta video permite ingresa video en la
página, contiene el atributo url para especificarle
la ubicación del video, sin embargo solo con este
atributo va a aparecer como una fotografía, por lo
que hay que colocar el atributo controls, otro atributo
es preload que no permite que el video se empiece a
renderizar apenas se ingrese a la página, existe tambien
el atributo para que el video comience a reporducirse apenas
se ingrese a la pagina, pero esta es muy mala practica,
podemos ingresar las etiquetas source para ingresar mas de
formato y sea el navegador el que busque el primero que
se encuentre-->
<video controls preload="auto">
<source src="./Video.mp4#t=10,15"/>
<source src="./Video.m4v#t=10,15"/>
</video>
</section>
</main>
</body>
</html>
|
import {keysOf} from "@lucilor/utils";
import {sample} from "lodash";
import {SkillSetGetter} from "./types";
export const getAomiSkillSet: SkillSetGetter = () => [
{
name: "aomi",
data: {
charlotte: true,
superCharlotte: true,
mark: true,
intro: {
content: (storage, player) => {
const skills = LucilorExt.getStorage<string[]>(player, "aomi", []);
const token = LucilorExt.getStorage(player, "aomi_token", 0);
const max = LucilorExt.getStorage(player, "aomi_max", 0);
const choose = LucilorExt.getStorage(player, "aomi_choose", 0);
const reviveCount = LucilorExt.getStorage(player, "aomi_reviveCount", 0);
const strs: string[] = [];
if (!skills || skills.length < 1) {
strs.push("未获得技能");
} else {
strs.push("已获得技能:" + LucilorExt.getColoredStr(get.translation(storage), "cyan"));
}
const maxStr = LucilorExt.getColoredStr(String(max), "orange");
const chooseStr = LucilorExt.getColoredStr(String(choose), "deeppink");
const tokenStr = LucilorExt.getColoredStr(String(token), "lightgreen");
const reviveCountStr = LucilorExt.getColoredStr(String(reviveCount), "lightgreen");
strs.push(`上限:${maxStr}`);
strs.push(`候选:${chooseStr}`);
strs.push(`代币:${tokenStr}`);
strs.push(`已使用复活币:${reviveCountStr}`);
return strs.join("<br>");
}
},
init: (player) => {
LucilorExt.setStorage(player, "aomi", []);
LucilorExt.setStorage(player, "aomi_token", 0);
LucilorExt.setStorage(player, "aomi_choose", 3);
LucilorExt.setStorage(player, "aomi_max", 3);
LucilorExt.setStorage(player, "aomi_reviveCount", 0);
},
ai: {
threaten: 1.5
},
group: LucilorExt.getSubSkillNames("aomi", ["before", "after", "dmgCount", "maxHp", "huishi", "dieBefore"]),
subSkill: {
before: {
trigger: {
global: "gameStart",
player: ["phaseBefore"]
},
priority: Infinity,
forced: true,
content: async (event, trigger, player) => {
await LucilorExt.skillHelper.discoverAomiSkill(event, player);
}
},
after: {
trigger: {
player: ["phaseAfter", "turnOverAfter"]
},
priority: -Infinity,
forced: true,
content: async (event, trigger, player) => {
await LucilorExt.skillHelper.discoverAomiSkill(event, player);
}
},
dmgCount: {
trigger: {
player: ["damageAfter", "loseHpAfter"]
},
forced: true,
priority: -1,
content: async (event, trigger, player) => {
let token0 = LucilorExt.getStorage(player, "aomi_token", 0);
token0 += trigger.num;
LucilorExt.setStorage(player, "aomi_token", token0);
player.say(`奥秘代币:${token0}`);
let isUpgraded = false;
// eslint-disable-next-line no-constant-condition
while (true) {
const token = LucilorExt.getStorage(player, "aomi_token", 0);
const max = LucilorExt.getStorage(player, "aomi_max", 0);
const choose = LucilorExt.getStorage(player, "aomi_choose", 0);
const aomiTeachableSkills = LucilorExt.skillHelper.getAomiTeachableSkillList(player);
const choices: string[] = [];
const cost = LucilorExt.skillHelper.getAomiUpgradeCost(player);
const choiceList = [
`技能库上限+1(当前${max},消耗${cost.max}代币)`,
`候选技能数量+1(当前${choose},消耗${cost.choose}代币)`,
`令一名其他角色获得技能库中的一个技能(消耗${cost.teach}代币)`
];
const chioceCancel = "不升级";
const chiocesAll = ["加上限", "加候选", "教别人", chioceCancel] as const;
const disableChoice = (i: number) => {
choiceList[i] = `<span style="opacity:0.5">${choiceList[i]}</span>`;
};
if (token >= cost.max) {
choices.push(chiocesAll[0]);
} else {
disableChoice(0);
}
if (token >= cost.choose) {
choices.push(chiocesAll[1]);
} else {
disableChoice(1);
}
if (token >= cost.teach && aomiTeachableSkills.length > 0) {
choices.push(chiocesAll[2]);
} else {
disableChoice(2);
}
if (choices.length > 0) {
choices.push(chioceCancel);
const title = `消耗代币升级奥秘技能库<br>当前代币:${token}`;
const result = await player
.chooseControl(choices)
.set("prompt", title)
.set("choiceList", choiceList)
.set("ai", () => {
const max = LucilorExt.getStorage(player, "aomi_max", 0);
const choose = LucilorExt.getStorage(player, "aomi_choose", 0);
if (max < choose && choices.includes(chiocesAll[0])) {
return chiocesAll[0];
}
if (choices.includes(chiocesAll[1])) {
return chiocesAll[1];
}
return choices.length > 0 ? choices[0] : chioceCancel;
})
.forResult();
const cost2 = LucilorExt.skillHelper.getAomiUpgradeCost(player);
let isUpgraded2 = false;
switch (result.control) {
case chiocesAll[0]:
LucilorExt.setStorageWith(player, "aomi_max", (val: number) => val + 1);
LucilorExt.setStorageWith(player, "aomi_token", (val: number) => val - cost2.max);
isUpgraded2 = true;
break;
case chiocesAll[1]:
LucilorExt.setStorageWith(player, "aomi_choose", (val: number) => val + 1);
LucilorExt.setStorageWith(player, "aomi_token", (val: number) => val - cost2.choose);
isUpgraded2 = true;
break;
case chiocesAll[2]: {
const result = await LucilorExt.skillHelper.chooseSkills(player, {
chooseFrom: aomiTeachableSkills,
chooseFromLabel: "拥有技能",
chooseTo: [],
chooseToLabel: "教授技能",
limit: 1
});
if (result) {
const skillToTeach = result.skills1[0].name;
if (skillToTeach) {
const result = await player
.chooseTarget(choiceList[2], (card: Card, player: Player, target: Player) => {
return target !== player && !target.hasSkill(skillToTeach);
})
.forResult();
if (result.bool) {
LucilorExt.setStorageWith(player, "aomi_token", (val: number) => val - cost2.teach);
player.line(result.targets, "green");
const target = result.targets[0];
LucilorExt.skillHelper.addSkillLog(skillToTeach, target);
LucilorExt.skillHelper.tryUseStartSkills(event, target, [skillToTeach]);
}
}
}
break;
}
}
if (isUpgraded2) {
isUpgraded = true;
} else {
break;
}
} else {
break;
}
}
if (isUpgraded) {
await LucilorExt.skillHelper.discoverAomiSkill(event, player);
}
},
ai: {
maixie: true,
maixie_hp: true,
maihp: true
}
},
maxHp: {
trigger: {
global: "roundStart"
},
forced: true,
content: async (event, trigger, player) => {
const players = game.players.filter((p) => p !== player);
const maxHp = Math.max(...players.map((p) => (isNaN(Number(p.maxHp)) ? 1 : Number(p.maxHp))));
if (player.maxHp < maxHp) {
player.gainMaxHp();
player.recover();
} else if (player.maxHp > maxHp) {
player.loseMaxHp();
}
}
},
huishi: {
trigger: {
global: "gameStart"
},
forced: true,
content: async (event, trigger, player: Player) => {
const shouldRemove = (card: Card) => ["zhuge", "rewrite_zhuge", ""].includes(card.name);
const toRemove: Card[] = [];
for (const pile of ["cardPile", "discardPile"] as const) {
const cards = Array.from(ui[pile].childNodes as NodeListOf<Card>).filter(shouldRemove);
if (cards.length > 0) {
toRemove.push(...cards);
player.$throw(cards, undefined, undefined, undefined);
}
}
for (const player of game.filterPlayer()) {
const cards = player.getCards("hej", shouldRemove);
if (cards.length) {
toRemove.push(...cards);
player.$throw(cards, undefined, undefined, undefined);
}
}
if (toRemove.length > 0) {
game.cardsGotoSpecial(toRemove);
game.log(toRemove, "被移出了游戏");
}
let targetIdentity: string | undefined;
if (player.identity === "zhu") {
targetIdentity = "zhong";
} else if (player.identity === "fan") {
targetIdentity = "fan";
}
const target = sample(game.filterPlayer((p) => p.identity === targetIdentity));
if (target) {
if (!_status.connectMode) {
if (player === game.me) {
target.setIdentity();
target.node.identity.classList.remove("guessing");
player.line(target, "green");
player.popup(LucilorExt.getSkillName("aomi"));
}
} else {
player
.chooseControl("ok")
.set("dialog", [`${get.translation(target)}是${get.translation(targetIdentity + "2")}`, [[target.name], "character"]]);
}
}
}
},
dieBefore: {
trigger: {
global: "dieBefore"
},
filter: (event, player) => 0 < LucilorExt.getStorage(player, "aomi_max", 0),
logTarget: "player",
skillAnimation: true,
animationColor: "thunder",
prompt: (event, player) => {
const name = event.player === player ? "自己" : get.translation(event.player);
return `是否发动【${get.translation(LucilorExt.getSkillName("aomi"))}】,对${name}使用复活币?`;
},
prompt2: (event, player) => {
const count = 1; // LucilorExt.getStorage(player, "aomi_reviveCount", 0);
const name = event.player === player ? "自己" : get.translation(event.player);
let str = "";
if (count > 0) {
str = `失去${count}技能库上限并`;
} else if (count < 0) {
str = `获得${-count}技能库上限并`;
}
return `${str}防止${name}死亡,其弃置判定区内的牌并复原武将牌,然后将体力回复至1并摸3张牌。`;
},
check: (event, player) => get.attitude(player, event.player) >= 3,
content: async (event, trigger, player) => {
const max = LucilorExt.getStorage(player, "aomi_max", 0);
if (max < 1) {
return;
}
LucilorExt.setStorageWith(player, "aomi_reviveCount", (val: number) => val + 1);
LucilorExt.setStorage(player, "aomi_max", max - 1);
trigger.cancel();
if (trigger.player.maxHp < 1) {
trigger.player.maxHp = 1;
}
await LucilorExt.skillHelper.discoverAomiSkill(event, player);
trigger.player.recover(1 - trigger.player.hp);
trigger.player.discard(trigger.player.getCards("j"));
trigger.player.turnOver(false);
trigger.player.link(false);
trigger.player.draw(3);
trigger.player.update();
}
}
}
},
translate: {
aomi: "奥秘",
aomi_info: [
`<font color="#ff92f9"<b>『学无止境』</b></font><br>锁定技,游戏开始时、回合开始前、回合结束后和你翻面后,休整技能库。你每受到1点伤害(或体力流失)后获得1枚代币,若此时代币足够升级,则升级技能库。`,
`<font color="#ff92f9"<b>『唯我独尊』</b></font><br>锁定技,每轮开始时,若你的体力上限:大于X,你减1点体力上限;小于X,你加1点体力上限并回复1点体力(X为其他角色的最大体力上限)。`,
`<font color="#ff92f9"<b>『慧识摘星』</b></font><br>锁定技,游戏开始时,你将所有【诸葛连弩】、【元戎精械弩】移出游戏。若你的身份为:主公,你随机得知一名忠臣的身份;反贼,你随机得知一名反贼的身份。`,
`<font color="#ff92f9"<b>『漫漫路远』</b></font><br>一名角色死亡前,你可以减少1技能库上限(若足够)并防止该角色死亡,其弃置判定区内的牌并复原武将牌,然后将体力回复至1并摸3张牌。`
].join("<br>")
},
tips: {
休整技能库: "从候选技能中选择获得或替换技能(若拥有技能多于上限,则需舍弃技能)。",
升级技能库: "游戏开始时技能库上限为3,候选技能数量为3。升级时可消耗代币选择升级选项。"
}
}
];
export const updateAomiSkills = async () => {
const getSkillAudio = (name: string): string => {
const skill = lib.skill[name];
if (!skill) {
return name;
}
const audio = skill.audio;
if (typeof audio === "string") {
return getSkillAudio(audio);
} else {
return name;
}
};
const audios = LucilorExt.aomiSkillConfig?.audios || {aomi: "", dmgCount: "", dieBefore: ""};
for (const key of keysOf(audios)) {
audios[key] = getSkillAudio(audios[key]);
}
const aomi = await LucilorExt.waitForSometing(() => LucilorExt.getSkill("aomi"));
if (aomi) {
aomi.audio = audios.aomi;
if (aomi.subSkill) {
aomi.subSkill.before.audio = audios.aomi;
aomi.subSkill.after.audio = audios.aomi;
aomi.subSkill.dmgCount.audio = audios.dmgCount;
aomi.subSkill.dieBefore.audio = audios.dieBefore;
}
}
};
|
import { SafeAreaView } from 'react-native-safe-area-context'
import { StyleSheet, Dimensions } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import HeroesList from '../../screens/Heroes/HeroesList';
import HeroAddForm from '../../screens/Heroes/HeroAddForm';
import { RootStackParamList } from '../../interfaces/types';
import Ionicons from '@expo/vector-icons/Ionicons';
import HeroEditForm from '../../screens/Heroes/HeroEditForm';
const screenHeight = Dimensions.get('window').height + 100;
export default function LoggedNavigation() {
return (
<NavigationContainer>
<SafeAreaView style={styles.safeArea}>
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: "#005",
// Cambia el color de fondo del encabezado
},
headerTitleAlign: 'center',
headerTintColor: '#fff', // Cambia el color de los botones y del título en el encabezado
headerTitleStyle: {
fontWeight: 'bold', // Fuente en negrita para el título
fontSize: 30, // Tamaño de la fuente para el título
},
animationTypeForReplace: "pop",
animation: "slide_from_bottom"
}}
>
<Stack.Screen
name="HeroesList"
component={HeroesList}
options={({ navigation }) => ({
title: 'Heroes List',
headerRight: () => (
<Ionicons
name='add-circle'
size={30}
color="white"
onPress={() => navigation.navigate('CreateHero')}
style={{ marginRight: 10 }}
/>
),
})}
/>
<Stack.Screen
name="CreateHero"
component={HeroAddForm}
options={({ navigation }) => ({
title: 'Create a Hero',
headerLeft: () => (
<Ionicons
name="arrow-down"
size={24}
color="white"
onPress={() => navigation.navigate('HeroesList')}
style={{ marginRight: 10 }}
/>
),
})}
/>
<Stack.Screen
name="EditHero"
component={HeroEditForm}
options={({ navigation, route }) => ({
title: 'Edit: ' + route.params.itemName,
headerTitleStyle: {
fontWeight: 'bold', // Fuente en negrita para el título
fontSize: 26, // Tamaño de la fuente para el título
},
headerLeft: () => (
<Ionicons
name="arrow-down"
size={24}
color="white"
onPress={() => navigation.navigate('HeroesList')}
style={{ marginRight: 10 }}
/>
),
})}
/>
</Stack.Navigator>
</SafeAreaView>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
safeArea: {
backgroundColor: "#005",
minHeight: screenHeight
}
});
const Stack = createNativeStackNavigator<RootStackParamList>();
|
//
// MapView.swift
// AnimalsPlus
//
// Created by Abdullah Bilgin on 7/30/23.
import SwiftUI
import MapKit
struct MapView: View {
// MARK: - PROPERTIES
@State private var region: MKCoordinateRegion = {
var mapCoordinates = CLLocationCoordinate2D(
latitude: 6.600286,
longitude: 16.4377599
)
var mapZoomLevel = MKCoordinateSpan(
latitudeDelta: 70.0,
longitudeDelta: 70.0
)
var mapRegion = MKCoordinateRegion(
center: mapCoordinates,
span: mapZoomLevel
)
return mapRegion
} ()
let locations: [NatinalParkLocation] = Bundle.main.decode("locations.json")
// MARK: - BODY
var body: some View {
// MARK: - No1 BASIC MAP
//Map(coordinateRegion: $region)
// MARK: - No2 ADVANCED MAP
Map(coordinateRegion: $region, annotationItems: locations, annotationContent: { item in
// (A) PIN: OLD STYLE (always static)
// MapPin(coordinate: item.location, tint: .accentColor)
// (B) MARKER: NEW STYLE (always static)
// MapMarker(coordinate: item.location, tint: .accentColor)
// (C) CUSTOM BASIC ANNOTATION: (it could be interactive)
// MapAnnotation(coordinate: item.location) {
// Image("logo")
// .resizable()
// .scaledToFit()
// .frame(width: 32, height: 32, alignment: .center)
// } // ANNOTATION
// (D) CUSTOM ADVANCED ANNOTATION (it could be interactive)
MapAnnotation(coordinate: item.location) {
MapAnnotationView(location: item)
}
}) //: MAP
.overlay(
HStack(alignment: .center, spacing: 12) {
Image("compass")
.resizable()
.scaledToFit()
.frame(width: 48, height: 48, alignment: .center)
VStack(alignment: .leading, spacing: 3) {
HStack {
Text("Latitude:")
.font(.footnote)
.font(.body)
.foregroundColor(.accentColor)
Spacer()
Text("\(region.center.latitude)")
.font(.footnote)
.foregroundColor(.white)
}
Divider()
HStack {
Text("Longitude:")
.font(.footnote)
.font(.body)
.foregroundColor(.accentColor)
Spacer()
Text("\(region.center.longitude)")
.font(.footnote)
.foregroundColor(.white)
}
}
} // HSTACK
.padding(.vertical, 12)
.padding(.horizontal, 16)
.background(
Color.black
.cornerRadius(8)
.opacity(0.6)
)
.padding()
, alignment: .top
)
}
}
// MARK: - PREVIEW
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView()
}
}
|
package com.example.warg.domain.views
import android.widget.Space
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.magnifier
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.example.warg.R
import com.example.warg.domain.components.Screen
import com.example.warg.domain.components.WargAuth
import com.example.warg.domain.components.WargTestAuth
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WargAuthentificationScreen (navHostController: NavHostController) {
var utilisateur by rememberSaveable { mutableStateOf("") }
var password by rememberSaveable { mutableStateOf("") }
Column(
modifier = Modifier.padding(vertical = 35.dp, horizontal = 25.dp),
verticalArrangement = Arrangement.Top
) {
Image(painter = painterResource(id = R.drawable.logo), contentDescription = stringResource(id = R.string.logo))
}
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.padding(vertical = 50.dp))
WargAuth(
modifier = Modifier,
user = utilisateur,
pass = password,
userChange = { utilisateur = it },
passChange = { password = it}
)
Row (
modifier = Modifier.padding(vertical = 10.dp)
){
Row(
horizontalArrangement = Arrangement.Start
) {
TextButton(onClick = { navHostController.navigate(route = "${Screen.WargInscription.route}") }) {
Text(text = "Créer un compte")
}
}
Spacer(modifier = Modifier.padding(horizontal = 20.dp))
WargTestAuth(username = utilisateur, password = password, navHostController = navHostController)
}
}
}
|
package com.jd.user.increase.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jd.user.increase.common.HttpResult;
import com.jd.user.increase.dao.GraphSnapshotDao;
import com.jd.user.increase.domain.GraphNodeData;
import com.jd.user.increase.domain.GraphEdgeData;
import com.jd.user.increase.domain.GraphSnapshot;
import com.jd.user.increase.domain.Person;
import com.jd.user.increase.service.GraphSnapshotService;
import com.jd.user.increase.utils.SortObjectIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 本类重点知识: 前后端分离,端口不一致导致跨域问题: @CrossOrigin(origins = "*", maxAge = 3600)
*/
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("hello")
@Slf4j
public class HelloController {
@Autowired
private GraphSnapshotService graphSnapshotService;
@Autowired
private GraphSnapshotDao graphSnapshotDao;
/**
* 测试方法
*
* @return
*/
@RequestMapping("/demo")
public String hello(@RequestBody Person person) {
log.info(person.toString());
return "欢迎进入后台";
}
/**
* 解析graph中data的方法
*
* @return
*/
@RequestMapping("/demo2")
public HttpResult hello2(@RequestBody String graphCells) throws InterruptedException {
log.info(graphCells);
ArrayList<GraphNodeData> cellDataList = new ArrayList<>();
// 1. 将cells中原始的画布数据转换成为标准的list
cellDataList = convertCells2Bean(graphCells);
// 2. 遍历list,解析数据,根据node的ID大小顺序执行
// 从小到大排序
SortObjectIDUtil sortObjectIDUtil = new SortObjectIDUtil();
Collections.sort(cellDataList, sortObjectIDUtil);
// 依次遍历执行
for (GraphNodeData item : cellDataList) {
String cellId = StringUtils.isEmpty(item.getCellId())? "" : item.getCellId();
// 第一步执行获取数据
String data = getData();
log.info("步骤1",data);
// 第二部执行判断,如果是A执行步骤3,否则执行步骤4
if ("A".equals(data)){
String step3 = executeStep3();
log.info(step3);
}
if ("B".equals(data)){
String step4 = executeStep4();
log.info(step4);
}
}
return new HttpResult(200, "success", cellDataList);
}
/**
* 保存graph方法
*/
@RequestMapping("/saveGraph")
public HttpResult saveGraph(@RequestBody String graphJson){
log.info("graphCells={}",graphJson);
String graphCells = JSON.parseObject(graphJson).get("cells").toString();
// 定义成员变量
GraphSnapshot graphSnapshot = new GraphSnapshot();
ArrayList<GraphNodeData> cellDataList = new ArrayList<>();
// 1. 将cells中原始的画布数据转换成为标准的list
// cellDataList = convertCells2Bean(graphCells);
// 2. 遍历list,解析数据,根据node的ID大小顺序执行
// 从小到大排序
// SortObjectIDUtil sortObjectIDUtil = new SortObjectIDUtil();
// Collections.sort(cellDataList, sortObjectIDUtil);
graphSnapshot.setGraphData(JSON.toJSONString(cellDataList));
graphSnapshot.setGraphSnapshot(graphJson);
graphSnapshot.setCreateUser("wangyongpeng11");
Integer rowNum = graphSnapshotService.insert(graphSnapshot);
return new HttpResult(200,"ok",rowNum);
}
/**
* 查询graph列表的方法
*/
@RequestMapping("/graphList")
public HttpResult graphList(){
// List<GraphSnapshot> snapshotList = graphSnapshotService.queryList();
List<GraphSnapshot> snapshotList = new ArrayList<>();
GraphSnapshot graphSnapshot = new GraphSnapshot();
String res = "{\"cells\":[{\"position\":{\"x\":420,\"y\":160},\"size\":{\"width\":80,\"height\":42},\"attrs\":{\"text\":{\"text\":\"起始节点\"},\"body\":{\"rx\":24,\"ry\":24}},\"shape\":\"flow-chart-rect\",\"data\":{\"id\":\"node-100\",\"type\":\"node\",\"cellText\":\"矩形节点文本\",\"value1\":\"矩形节点文本value1\",\"value2\":\"矩形节点文本value2\",\"value3\":\"矩形节点文本value3\",\"sourceId\":\"10\",\"targetId\":\"10\",\"previousNodeId\":\"10\",\"nextNodeId\":\"10\"},\"ports\":{\"groups\":{\"top\":{\"position\":\"top\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"right\":{\"position\":\"right\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"bottom\":{\"position\":\"bottom\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"left\":{\"position\":\"left\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}}},\"items\":[{\"group\":\"top\",\"id\":\"45726225-0a03-409e-8475-07da4b8533c5\"},{\"group\":\"right\",\"id\":\"06111939-bf01-48d9-9f54-6465d9d831c6\"},{\"group\":\"bottom\",\"id\":\"6541f8dc-e48b-4b8c-a105-2ab3a47f1f21\"},{\"group\":\"left\",\"id\":\"54781206-573f-4982-a21e-5fac1e0e8a60\"}]},\"id\":\"8650a303-3568-4ff2-9fac-2fd3ae7e6f2a\",\"zIndex\":1},{\"position\":{\"x\":420,\"y\":250},\"size\":{\"width\":80,\"height\":42},\"attrs\":{\"text\":{\"text\":\"流程节点\"}},\"shape\":\"flow-chart-rect\",\"data\":{\"id\":\"node-100\",\"type\":\"node\",\"cellText\":\"矩形节点文本\",\"value1\":\"矩形节点文本value1\",\"value2\":\"矩形节点文本value2\",\"value3\":\"矩形节点文本value3\",\"sourceId\":\"10\",\"targetId\":\"10\",\"previousNodeId\":\"10\",\"nextNodeId\":\"10\"},\"ports\":{\"groups\":{\"top\":{\"position\":\"top\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"right\":{\"position\":\"right\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"bottom\":{\"position\":\"bottom\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"left\":{\"position\":\"left\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}}},\"items\":[{\"group\":\"top\",\"id\":\"d1346f43-969a-4201-af5d-d09b7ef79980\"},{\"group\":\"right\",\"id\":\"d561926a-3a24-449a-abb1-0c20bc89947e\"},{\"group\":\"bottom\",\"id\":\"0cbde5df-ef35-410e-b6c3-a6b1f5561e3f\"},{\"group\":\"left\",\"id\":\"2fceb955-f7af-41ac-ac02-5a2ea514544e\"}]},\"id\":\"7b6fd715-83e6-4053-8c2b-346e6a857bf3\",\"zIndex\":2},{\"shape\":\"edge\",\"attrs\":{\"line\":{\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"targetMarker\":{\"name\":\"classic\",\"size\":8}}},\"id\":\"00f3c401-8bad-46b9-b692-232aa011d4c5\",\"router\":{\"name\":\"manhattan\"},\"zIndex\":3,\"source\":{\"cell\":\"8650a303-3568-4ff2-9fac-2fd3ae7e6f2a\",\"port\":\"6541f8dc-e48b-4b8c-a105-2ab3a47f1f21\"},\"target\":{\"cell\":\"7b6fd715-83e6-4053-8c2b-346e6a857bf3\",\"port\":\"d1346f43-969a-4201-af5d-d09b7ef79980\"},\"labels\":[{\"attrs\":{\"label\":{\"text\":\"edge\"}}}]}]}\n";
snapshotList = graphSnapshotDao.queryList();
log.info("snapshotList = {}",snapshotList);
return HttpResult.buildSuccessResult(snapshotList);
}
/**
* 根据ID查询一条graph的方法
*/
@RequestMapping("/queryById")
public HttpResult queryById(@RequestBody String graphId){
String id = JSON.parseObject(graphId).get("graphId").toString();
GraphSnapshot graphSnapshot = new GraphSnapshot();
graphSnapshot = graphSnapshotDao.queryById(Long.valueOf(id));
return HttpResult.buildSuccessResult(graphSnapshot);
}
/**
* 将cells中原始的画布数据转换成为标准的list
* @param graphCells
* @return
*/
private ArrayList<GraphNodeData> convertCells2Bean(String graphCells) {
ArrayList<GraphNodeData> cellDataList = new ArrayList<>();
// 1. 将jsonBody解析成数组
JSONArray jsonArray = JSONArray.parseArray(graphCells);
// 2. 遍历数组
for (int i = 0; i < jsonArray.size(); i++) {
// 3. 将数组中每个cell元素解析成对象,并去除对象中的data对象,
JSONObject jsonObjectString = JSON.parseObject(String.valueOf(jsonArray.get(i)));
// 此时jsonObject还是string,需要解析成对象
log.info("jsonObject = {}", jsonObjectString);
JSONObject parseObject = JSON.parseObject(String.valueOf(jsonObjectString));
if (!"edge".equals(parseObject.get("shape"))) {
// 此时 parseObject.get("data") 还是string,需要解析成对象
GraphNodeData cellData = JSON.parseObject(String.valueOf(parseObject.get("data")), GraphNodeData.class);
cellDataList.add(cellData);
}
}
log.info("list = {}",cellDataList);
return cellDataList;
}
/**
* 将cells中原始的画布数据转换成为标准的list
* @param graphCells
* @return
*/
private ArrayList<GraphNodeData> convertCells2BeanV2(String graphCells) {
ArrayList<GraphNodeData> cellDataList = new ArrayList<>();
// 1. 将jsonBody解析成数组
JSONArray jsonArray = JSONArray.parseArray(graphCells);
// 2. 遍历数组
for (int i = 0; i < jsonArray.size(); i++) {
// 3. 将数组中每个cell元素解析成对象,并去除对象中的data对象,
JSONObject jsonObjectString = JSON.parseObject(String.valueOf(jsonArray.get(i)));
// 此时jsonObject还是string,需要解析成对象
log.info("jsonObject = {}", jsonObjectString);
JSONObject parseObject = JSON.parseObject(String.valueOf(jsonObjectString));
if (!"edge".equals(parseObject.get("shape"))) {
// 此时 parseObject.get("data") 还是string,需要解析成对象
GraphNodeData cellData = JSON.parseObject(String.valueOf(parseObject.get("data")), GraphNodeData.class);
cellDataList.add(cellData);
}
}
log.info("list = {}",cellDataList);
return cellDataList;
}
/**
* 执行单一,没有判断节点的指令流程 :
* 1. 拿到graph的原始数据
* 2. 根据边的信息将每个节点的source,target,nextNode数据填充完整
* 3.
* @return
*/
@RequestMapping("/run")
public HttpResult runGraph(@RequestBody String graphSnapshot){
// 存储节点数据
List<GraphNodeData> graphNodeDataList = new ArrayList<>();
// 存储边数据
List<GraphEdgeData> graphEdgeDataList = new ArrayList<>();
// graphSnapshot = "{\"cells\":[{\"position\":{\"x\":20,\"y\":-130},\"size\":{\"width\":80,\"height\":42},\"attrs\":{\"text\":{\"text\":\"start\"},\"body\":{\"fill\":\"#F70909\",\"rx\":24,\"ry\":24}},\"shape\":\"flow-chart-rect\",\"data\":{\"cellId\":\"node-100\",\"type\":\"node\",\"cellText\":\"起始节点文本\",\"value1\":\" i = 0\",\"value2\":\"j = 0\",\"value3\":\"起始节点value3\",\"sourceId\":\"10\",\"targetId\":\"10\",\"previousNodeId\":\"10\",\"nextNodeId\":\"10\",\"id\":\"node-100\"},\"ports\":{\"groups\":{\"top\":{\"position\":\"top\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"right\":{\"position\":\"right\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"bottom\":{\"position\":\"bottom\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"left\":{\"position\":\"left\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}}},\"items\":[{\"group\":\"top\",\"id\":\"1d2f204a-6138-4280-a120-7c5b870549ad\"},{\"group\":\"right\",\"id\":\"276402a9-c175-4af5-a66e-66796151c278\"},{\"group\":\"bottom\",\"id\":\"33347108-be5a-42d6-9c75-b3bb2d18a069\"},{\"group\":\"left\",\"id\":\"bd6e56b4-55e0-46b9-9527-6bb1ddc5b549\"}]},\"id\":\"ae4f7117-c410-4486-b936-464f3db9edfd\",\"zIndex\":1},{\"position\":{\"x\":20,\"y\":-40},\"size\":{\"width\":80,\"height\":42},\"attrs\":{\"text\":{\"text\":\"step1:数据\"},\"body\":{\"fill\":\"#0DDD1DF7\"}},\"shape\":\"flow-chart-rect\",\"data\":{\"cellId\":\"node-100\",\"type\":\"node\",\"cellText\":\"流程节点\",\"value1\":\"i = 5\",\"value2\":\"j = 50\",\"value3\":\"流程节点value3\",\"sourceId\":\"10\",\"targetId\":\"10\",\"previousNodeId\":\"10\",\"nextNodeId\":\"10\",\"id\":\"node-101\"},\"ports\":{\"groups\":{\"top\":{\"position\":\"top\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"right\":{\"position\":\"right\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"bottom\":{\"position\":\"bottom\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"left\":{\"position\":\"left\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}}},\"items\":[{\"group\":\"top\",\"id\":\"7ade9a4a-5d26-4bb0-a471-f443106167e5\"},{\"group\":\"right\",\"id\":\"2aaf772e-c228-4617-a3c2-7d81023797fc\"},{\"group\":\"bottom\",\"id\":\"7471cc77-6aa9-4665-80c7-d67377bb27f1\"},{\"group\":\"left\",\"id\":\"87419b03-ff19-40b3-afca-adceda3b0898\"}]},\"id\":\"ce1838bb-7cc8-4ee2-9080-113b10ac210a\",\"zIndex\":2},{\"shape\":\"edge\",\"attrs\":{\"line\":{\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"targetMarker\":{\"name\":\"classic\",\"size\":8}}},\"id\":\"eb04847a-97e2-4dad-a240-e940b13de727\",\"router\":{\"name\":\"manhattan\"},\"source\":{\"cell\":\"ae4f7117-c410-4486-b936-464f3db9edfd\",\"port\":\"33347108-be5a-42d6-9c75-b3bb2d18a069\"},\"target\":{\"cell\":\"ce1838bb-7cc8-4ee2-9080-113b10ac210a\",\"port\":\"7ade9a4a-5d26-4bb0-a471-f443106167e5\"},\"zIndex\":3},{\"position\":{\"x\":20,\"y\":50},\"size\":{\"width\":80,\"height\":42},\"attrs\":{\"text\":{\"text\":\"step2: 计算\"},\"body\":{\"fill\":\"#FF5F5FF0\"}},\"shape\":\"flow-chart-rect\",\"data\":{\"cellId\":\"node-100\",\"type\":\"node\",\"cellText\":\"流程节点\",\"value1\":\"x = i + j\",\"value2\":\"x = 55\",\"value3\":\"流程节点value3\",\"sourceId\":\"10\",\"targetId\":\"10\",\"previousNodeId\":\"10\",\"nextNodeId\":\"10\",\"id\":\"node-101\"},\"ports\":{\"groups\":{\"top\":{\"position\":\"top\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"right\":{\"position\":\"right\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"bottom\":{\"position\":\"bottom\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"left\":{\"position\":\"left\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}}},\"items\":[{\"group\":\"top\",\"id\":\"7ade9a4a-5d26-4bb0-a471-f443106167e5\"},{\"group\":\"right\",\"id\":\"2aaf772e-c228-4617-a3c2-7d81023797fc\"},{\"group\":\"bottom\",\"id\":\"7471cc77-6aa9-4665-80c7-d67377bb27f1\"},{\"group\":\"left\",\"id\":\"87419b03-ff19-40b3-afca-adceda3b0898\"}]},\"id\":\"7cd3c8fe-b27c-47c3-a088-6ba33002e5ac\",\"zIndex\":4},{\"shape\":\"edge\",\"attrs\":{\"line\":{\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"targetMarker\":{\"name\":\"classic\",\"size\":8}}},\"id\":\"85d72d91-031a-4ecb-8fa7-13582c3ee9e1\",\"router\":{\"name\":\"manhattan\"},\"source\":{\"cell\":\"ce1838bb-7cc8-4ee2-9080-113b10ac210a\",\"port\":\"7471cc77-6aa9-4665-80c7-d67377bb27f1\"},\"target\":{\"cell\":\"7cd3c8fe-b27c-47c3-a088-6ba33002e5ac\",\"port\":\"7ade9a4a-5d26-4bb0-a471-f443106167e5\"},\"zIndex\":5},{\"position\":{\"x\":20,\"y\":142},\"size\":{\"width\":80,\"height\":42},\"attrs\":{\"text\":{\"text\":\"step3:存储\"},\"body\":{\"fill\":\"#A85FFF\"}},\"shape\":\"flow-chart-rect\",\"data\":{\"cellId\":\"node-100\",\"type\":\"node\",\"cellText\":\"流程节点\",\"value1\":\"存储i\",\"value2\":\"存储J\",\"value3\":\"流程节点value3\",\"sourceId\":\"10\",\"targetId\":\"10\",\"previousNodeId\":\"10\",\"nextNodeId\":\"10\",\"id\":\"node-101\"},\"ports\":{\"groups\":{\"top\":{\"position\":\"top\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"right\":{\"position\":\"right\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"bottom\":{\"position\":\"bottom\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"left\":{\"position\":\"left\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}}},\"items\":[{\"group\":\"top\",\"id\":\"7ade9a4a-5d26-4bb0-a471-f443106167e5\"},{\"group\":\"right\",\"id\":\"2aaf772e-c228-4617-a3c2-7d81023797fc\"},{\"group\":\"bottom\",\"id\":\"7471cc77-6aa9-4665-80c7-d67377bb27f1\"},{\"group\":\"left\",\"id\":\"87419b03-ff19-40b3-afca-adceda3b0898\"}]},\"id\":\"e41dca4b-ed0c-491a-934f-1281359a443c\",\"zIndex\":6},{\"shape\":\"edge\",\"attrs\":{\"line\":{\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"targetMarker\":{\"name\":\"classic\",\"size\":8}}},\"id\":\"50fd2857-2f70-48e2-aa57-f18d125db0d0\",\"router\":{\"name\":\"manhattan\"},\"source\":{\"cell\":\"7cd3c8fe-b27c-47c3-a088-6ba33002e5ac\",\"port\":\"7471cc77-6aa9-4665-80c7-d67377bb27f1\"},\"target\":{\"cell\":\"e41dca4b-ed0c-491a-934f-1281359a443c\",\"port\":\"7ade9a4a-5d26-4bb0-a471-f443106167e5\"},\"zIndex\":7},{\"position\":{\"x\":25,\"y\":238},\"size\":{\"width\":70,\"height\":70},\"attrs\":{\"text\":{\"text\":\"end\"},\"body\":{\"fill\":\"#FF5F5F\",\"rx\":35,\"ry\":35}},\"shape\":\"flow-chart-rect\",\"data\":{\"cellId\":\"node-100\",\"type\":\"node\",\"cellText\":\"矩形节点文本\",\"value1\":\"end1\",\"value2\":\"end2\",\"value3\":\"矩形节点文本value3\",\"sourceId\":\"10\",\"targetId\":\"10\",\"previousNodeId\":\"10\",\"nextNodeId\":\"10\"},\"ports\":{\"groups\":{\"top\":{\"position\":\"top\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"right\":{\"position\":\"right\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"bottom\":{\"position\":\"bottom\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}},\"left\":{\"position\":\"left\",\"attrs\":{\"circle\":{\"r\":3,\"magnet\":true,\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"fill\":\"#fff\",\"style\":{\"visibility\":\"hidden\"}}}}},\"items\":[{\"group\":\"top\",\"id\":\"8ce8eb80-f6c5-41ed-8bad-cfc067a232c4\"},{\"group\":\"right\",\"id\":\"d47f1ecb-d5f7-432a-8343-924cc6c68f84\"},{\"group\":\"bottom\",\"id\":\"eb674d18-005d-4e1d-a535-73896fc714b4\"},{\"group\":\"left\",\"id\":\"0bb01f3f-48b8-4f00-bc05-682528214762\"}]},\"id\":\"6044928f-e9e8-4412-92c5-dd1c92d239b6\",\"zIndex\":8},{\"shape\":\"edge\",\"attrs\":{\"line\":{\"stroke\":\"#5F95FF\",\"strokeWidth\":1,\"targetMarker\":{\"name\":\"classic\",\"size\":8}}},\"id\":\"90d07072-cad3-4ba7-9734-cc1743d031a6\",\"router\":{\"name\":\"manhattan\"},\"source\":{\"cell\":\"e41dca4b-ed0c-491a-934f-1281359a443c\",\"port\":\"7471cc77-6aa9-4665-80c7-d67377bb27f1\"},\"target\":{\"cell\":\"6044928f-e9e8-4412-92c5-dd1c92d239b6\",\"port\":\"8ce8eb80-f6c5-41ed-8bad-cfc067a232c4\"},\"zIndex\":9}]}";
JSONObject graphCellObject = JSON.parseObject(graphSnapshot);
String graphCells = graphCellObject.get("cells").toString();
// 1. 将jsonBody解析成数组
JSONArray jsonArray = JSONArray.parseArray(graphCells);
// 2. 遍历数组, 找出start 节点
// for (int i = 0; i < jsonArray.size(); i++) {
// // 3. 将数组中每个cell元素解析成对象,并去除对象中的data对象,
// JSONObject jsonObjectString = JSON.parseObject(String.valueOf(jsonArray.get(i)));
// // 此时jsonObject还是string,需要解析成对象
// log.info("jsonObject = {}", jsonObjectString);
// JSONObject parseObject = JSON.parseObject(String.valueOf(jsonObjectString));
// // 首先需要找出start节点
// if ("flow-chart-start".equals(parseObject.get("shape"))){
// // 此时 parseObject.get("data") 还是string,需要解析成对象
// GraphCellData cellData = JSON.parseObject(String.valueOf(parseObject.get("data")), GraphCellData.class);
// graphCellDataList.add(cellData);
// }
// }
// 遍历数组,先找出每一个node,赋值其id,type,等属性 然后再遍历边,让node串联起来
for (int i = 0; i < jsonArray.size(); i++){
// 3. 将数组中每个cell元素解析成对象,并去除对象中的data对象,
JSONObject jsonObjectString = JSON.parseObject(String.valueOf(jsonArray.get(i)));
// 此时jsonObject还是string,需要解析成对象
JSONObject parseObject = JSON.parseObject(String.valueOf(jsonObjectString));
// 首先整理node节点
if (!"edge".equals(parseObject.get("shape"))){
// 此时 parseObject.get("data") 还是string,需要解析成对象
GraphNodeData cellData = JSON.parseObject(String.valueOf(parseObject.get("data")), GraphNodeData.class);
// 赋值id,shape, cellText
cellData.setCellId((String) parseObject.get("id"));
cellData.setCellType((String) parseObject.get("shape"));
cellData.setCellText(JSON.parseObject(
JSON.parseObject(parseObject.get("attrs").toString()).get("text").toString()
).get("text").toString());
graphNodeDataList.add(cellData);
}else if ("edge".equals(parseObject.get("shape"))){
// 整理边节点
GraphEdgeData edgeData = new GraphEdgeData();
edgeData.setCellId((String) parseObject.get("id"));
// 设置source target
edgeData.setSourceNodeId(JSON.parseObject(parseObject.get("source").toString()).get("cell").toString());
edgeData.setTargetNodeId(JSON.parseObject(parseObject.get("target").toString()).get("cell").toString());
graphEdgeDataList.add(edgeData);
}
}
// 然后再遍历边节点List,将node节点赋值串联起来
for (GraphEdgeData edgeData : graphEdgeDataList) {
// 遍历节点集合
for (int i = 0; i < graphNodeDataList.size(); i++){
if (edgeData.getSourceNodeId().equals(graphNodeDataList.get(i).getCellId())){
graphNodeDataList.get(i).setyNextNodeId(edgeData.getTargetNodeId());
break;
}
}
}
return HttpResult.buildSuccessResult(graphNodeDataList);
// return HttpResult.buildSuccessResult(graphEdgeDataList);
}
private String executeStep4() {
return "A";
}
private String executeStep3() {
return "A";
}
private String getData() {
return "A";
}
}
|
from django.db import models
import uuid
import random
class BaseModel(models.Model):
uid= models.UUIDField(primary_key=True, default=uuid.uuid4,editable=False)
create_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now=True)
class Meta:
abstract=True
class Category(BaseModel):
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name
class Question(BaseModel):
category=models.ForeignKey(Category, related_name='category',on_delete=models.CASCADE)
question = models.CharField(max_length=100)
marks= models.IntegerField(default=5)
def __str__(self):
return self.question
def get_answers(self):
answer_objs=list(Answer.objects.filter(question=self))
random.shuffle(answer_objs)
data=[]
for answer_obj in answer_objs:
data.append({
'answer':answer_obj.answer,
'is_correct':answer_obj.is_correct,
})
return data
class Answer(BaseModel):
question= models.ForeignKey(Question, related_name='question_answer',on_delete=models.CASCADE)
answer = models.CharField(max_length=100)
is_correct= models.BooleanField(default=False)
def __str__(self) -> str:
return self.answer
|
use starknet::ContractAddress;
#[starknet::contract]
mod TokenBridge {
use nimbora_yields::token_bridge::interface::{
ITokenBridge, IMintableTokenDispatcher, IMintableTokenDispatcherTrait
};
use openzeppelin::upgrades::UpgradeableComponent;
use openzeppelin::{token::erc20::interface::{IERC20CamelDispatcher, IERC20CamelDispatcherTrait}};
use starknet::{
get_caller_address, contract_address::{Felt252TryIntoContractAddress}, syscalls::send_message_to_l1_syscall,
Zeroable, ClassHash
};
use super::{ContractAddress};
const ZERO_ADDRESS: felt252 = 'ZERO_ADDRESS';
const ZERO_AMOUNT: felt252 = 'ZERO_AMOUNT';
const INCORRECT_BALANCE: felt252 = 'INCORRECT_BALANCE';
const INSUFFICIENT_FUNDS: felt252 = 'INSUFFICIENT_FUNDS';
const UNINITIALIZED_L1_BRIDGE_ADDRESS: felt252 = 'UNINITIALIZED_L1_BRIDGE';
const EXPECTED_FROM_BRIDGE_ONLY: felt252 = 'EXPECTED_FROM_BRIDGE';
const UNINITIALIZED_TOKEN: felt252 = 'UNINITIALIZED_TOKEN';
const WITHDRAW_MESSAGE: felt252 = 0;
component!(path: UpgradeableComponent, storage: upgradeable, event: UpgradeableEvent);
impl InternalUpgradeableImpl = UpgradeableComponent::InternalImpl<ContractState>;
#[storage]
struct Storage {
#[substorage(v0)]
upgradeable: UpgradeableComponent::Storage,
_l2_address: ContractAddress,
_l1_bridge: felt252,
}
#[event]
#[derive(Drop, starknet::Event)]
enum Event {
#[flat]
UpgradeableEvent: UpgradeableComponent::Event,
WithdrawInitiated: WithdrawInitiated,
DepositHandled: DepositHandled,
}
#[derive(Drop, starknet::Event)]
struct WithdrawInitiated {
l1_recipient: felt252,
amount: u256,
caller_address: ContractAddress
}
#[derive(Drop, starknet::Event)]
struct DepositHandled {
account: felt252,
amount: u256
}
/// @notice Constructor for the contract, initializing it with the L2 token and L1 bridge addresses.
/// @param l2_address The address of the L2 token contract.
/// @param l1_bridge The address of the L1 bridge contract.
/// @dev Ensures that neither the L2 token address nor the L1 bridge address is zero before initializing the contract state.
#[constructor]
fn constructor(ref self: ContractState, l2_address: ContractAddress, l1_bridge: felt252) {
assert(l2_address.is_non_zero(), ZERO_ADDRESS);
assert(l1_bridge.is_non_zero(), ZERO_ADDRESS);
self._l2_address.write(l2_address);
self._l1_bridge.write(l1_bridge);
}
/// @notice Upgrade contract
/// @param New contract class hash
#[external(v0)]
fn upgrade(ref self: ContractState, new_class_hash: ClassHash) {
self.upgradeable._upgrade(new_class_hash);
}
#[abi(embed_v0)]
impl TokenBridgeImpl of ITokenBridge<ContractState> {
/// @notice Retrieves the address of the L2 token contract.
/// @return The address of the L2 token contract.
fn get_l2_token(self: @ContractState) -> ContractAddress {
self._l2_address.read()
}
/// @notice Retrieves the address of the L1 bridge contract.
/// @return The address of the L1 bridge contract.
fn get_l1_bridge(self: @ContractState) -> felt252 {
self._l1_bridge.read()
}
/// @notice Initiates a withdrawal process from L2 to L1.
/// @param l1_recipient The address of the recipient on L1.
/// @param amount The amount to withdraw.
/// @dev Performs checks on the amount, L1 bridge, and L2 token addresses before proceeding with the withdrawal.
/// Verifies the caller's balance before and after burning the L2 tokens, and sends a message to L1.
fn initiate_withdraw(ref self: ContractState, l1_recipient: felt252, amount: u256) {
assert(amount != 0, ZERO_AMOUNT);
// Check token and bridge addresses are valid.
let l1_bridge = self._l1_bridge.read();
assert(l1_bridge.is_non_zero(), ZERO_ADDRESS);
let l2_token = self._l2_address.read();
assert(l2_token.is_non_zero(), ZERO_ADDRESS);
// Call burn on l2_token contract and verify success.
let caller_address = get_caller_address();
let balance_before = IERC20CamelDispatcher { contract_address: l2_token }.balanceOf(caller_address);
assert(amount <= balance_before, INSUFFICIENT_FUNDS);
let mintable_token = IMintableTokenDispatcher { contract_address: l2_token };
mintable_token.permissioned_burn(caller_address, amount);
let balance_after = IERC20CamelDispatcher { contract_address: l2_token }.balanceOf(caller_address);
assert(balance_after == balance_before - amount, INCORRECT_BALANCE);
// Send the message.
let mut message_payload: Array<felt252> = ArrayTrait::new();
message_payload.append(WITHDRAW_MESSAGE);
message_payload.append(l1_recipient);
message_payload.append(amount.low.into());
message_payload.append(amount.high.into());
send_message_to_l1_syscall(to_address: l1_bridge, payload: message_payload.span());
self
.emit(
Event::WithdrawInitiated(
WithdrawInitiated { l1_recipient: l1_recipient, amount: amount, caller_address: caller_address }
)
);
}
/// @notice Sets the address of the L2 token contract.
/// @param l2_token_address The address of the new L2 token contract.
/// @dev Ensures that the provided L2 token address is not zero before updating the contract state.
fn set_l2_token(ref self: ContractState, l2_token_address: ContractAddress) {
assert(l2_token_address.is_non_zero(), ZERO_ADDRESS);
self._l2_address.write(l2_token_address);
}
/// @notice Sets the address of the L1 bridge contract.
/// @param l1_bridge_address The address of the new L1 bridge contract.
/// @dev Ensures that the provided L1 bridge address is not zero before updating the contract state.
fn set_l1_bridge(ref self: ContractState, l1_bridge_address: felt252) {
assert(l1_bridge_address.is_non_zero(), ZERO_ADDRESS);
self._l1_bridge.write(l1_bridge_address);
}
/// @notice Handles the deposit process from L1 to L2.
/// @param from_address The address of the sender on L1.
/// @param account The L2 account receiving the deposit.
/// @param amount The amount being deposited.
/// @dev Ensures the validity of account, L1 bridge, and L2 token addresses before proceeding.
/// Checks that the deposit was initiated by the L1 bridge, mints L2 tokens, and verifies the updated balance.
fn handle_deposit(ref self: ContractState, from_address: felt252, account: felt252, amount: u256) {
// Check account address is valid.
assert(account.is_non_zero(), ZERO_ADDRESS);
// Check token and bridge addresses are initialized and the handler invoked by the bridge.
let l1_bridge = self._l1_bridge.read();
assert(l1_bridge.is_non_zero(), UNINITIALIZED_L1_BRIDGE_ADDRESS);
assert(from_address == l1_bridge, EXPECTED_FROM_BRIDGE_ONLY);
let l2_token = self._l2_address.read();
assert(l2_token.is_non_zero(), UNINITIALIZED_TOKEN);
// Call mint on l2_token contract and verify success.
let balance_before = IERC20CamelDispatcher { contract_address: l2_token }
.balanceOf(account.try_into().unwrap());
let mintable_token = IMintableTokenDispatcher { contract_address: l2_token };
mintable_token.permissioned_mint(account.try_into().unwrap(), amount);
let balance_after = IERC20CamelDispatcher { contract_address: l2_token }
.balanceOf(account.try_into().unwrap());
assert(balance_after == balance_before + amount, INCORRECT_BALANCE);
self.emit(Event::DepositHandled(DepositHandled { account: account, amount: amount }));
}
}
}
|
import React,{useEffect, useState} from 'react';
import SearchIcon from './search.svg';
import MovieCard from './MovieCard';
const Api= "https://www.omdbapi.com?apikey=ea493709";
const Main=()=>{
const [movies,setMovies]=useState([]);
const [dearch,setdearch]=useState("");
const GetApi=async (title)=>{
const res=await fetch(`${Api}&s=${title}`);
const data=await res.json();
console.log(data.Search);
setMovies(data.Search);
}
useEffect(() => {
GetApi('batman');
},[]);
return(
<div className='app'>
<h1>Moviesssss!!!</h1>
<div className='search'>
<input
placeholder='Search for movies'
value={dearch}
onChange={(e)=>{
setdearch(e.target.value)
}}
/>
<img
src={SearchIcon}
alt="search icon"
onClick={()=>{
GetApi(dearch)
}}
/>
</div>
{
movies?.length > 0 ?(
<div className='container'>
{ movies.map((movie)=>{
return(
<MovieCard movie1={movie} />
)}) }
</div>
) :
(
<div className='empty'>
<h2>No Movie Found</h2>
</div>
)
}
</div>
);
}
export default Main;
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Transaksi;
use App\Models\Margin;
use App\Models\SalesOrder;
use App\Models\DeliveryOrder;
use App\Models\Customer;
use App\Charts\MarginChart;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Exception;
use PDOException;
use Carbon\Carbon;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index(MarginChart $chart)
{
$chartData = $chart->build();
$Ap = DB::table('deliveryorder')
->leftJoin('payment_order', 'deliveryorder.id_do', '=', 'payment_order.id_do')
->select('payment_order.hutang','payment_order.created_at')
->where('deliveryorder.status', 0)
// ->sum('payment_order.hutang')
->get();
$Ar = DB::table('salesorder')
->leftJoin('payment_so', 'salesorder.id_so', '=', 'payment_so.id_so')
->select('payment_so.hutang_customer','payment_so.created_at')
->where('salesorder.status', 0)
->get();
$totalDo = DB::table('deliveryorder')
->selectRaw('SUM(hargaPerKg * total_kg) as total_harga')
->where('tanggal_pembelian', '>=', now()->subDay())
->get();
$deliveryOrderData = DB::table('deliveryorder')
->select(
'deliveryorder.id_so',
'deliveryorder.id_do',
'deliveryorder.tanggal_pembelian as tanggal_pembelian',
'deliveryorder.hargaPerKg as harga_pembelian',
'deliveryorder.total_kg as total_kg',
'deliveryorder.etoll as etoll',
'deliveryorder.uang_jalan as uang_jalan', // Seharusnya uang_jalan
'deliveryorder.uang_tangkap as uang_tangkap',
'deliveryorder.solar as solar',
'deliveryorder.keterangan as keterangan',
'customer.id_customer',
'customer.nama as nama_customer',
'customer.nomor_telepon as nomor_telepon',
'customer.alamat as alamat',
'suplier.nama_suplier as nama_suplier',
'salesorder.tanggal as tanggal_penjualan',
'salesorder.hargaPerKg as harga_penjualan',
'salesorder.jumlahKg as jumlah_pembelian',
'verifikasi.id_verifikasi',
'verifikasi.gp_rp as gp_rp',
'verifikasi.gp as gp',
'verifikasi.tonase_akhir as tonase_akhir',
'verifikasi.normal as normal',
// ... (other columns you need)
)
->leftJoin('salesorder', 'deliveryorder.id_so', '=', 'salesorder.id_so')
->leftJoin('verifikasi', 'deliveryorder.id_do', '=', 'verifikasi.id_do')
->leftJoin('suplier', 'deliveryorder.id_suplier', '=', 'suplier.id_suplier')
->leftJoin('customer', 'salesorder.id_customer', '=', 'customer.id_customer')
->whereNotNull('verifikasi.id_do')
->get();
$increment = 1; // Inisialisasi increment
$marginData = [];
$totalMargin = 0;
foreach ($deliveryOrderData as $do) {
$transaksi_id = "TRANS-" . str_pad($increment, 5, '0', STR_PAD_LEFT);
$harga_total_beli = $do->total_kg * $do->harga_pembelian;
$gp_total = $do->gp * $do->gp_rp;
$margin_kg = $do->harga_penjualan - $do->harga_pembelian;
$normal = $do->harga_penjualan * $do->tonase_akhir;
$penjualan_akhir = $gp_total + $normal;
$margin_harian = $penjualan_akhir - $harga_total_beli;
$total_operational = $do->uang_jalan + $do->uang_tangkap + $do->solar + $do->etoll;
$laba = $margin_harian - $total_operational;
$marginData[] = [
'Transaksi ID' => $transaksi_id,
'ID Penjualan' => $do->id_so,
'Nama Customer' => $do->nama_customer,
'ID Pembelian' => $do->id_do,
'Nama Suplier' => $do->nama_suplier,
'Tanggal Penjualan' => $do->tanggal_penjualan,
'Tanggal Pembelian' => $do->tanggal_pembelian,
'Harga Penjualan' => $do->harga_penjualan,
'Harga Pembelian' => $do->harga_pembelian,
'Margin Harian' => $margin_harian,
'Keterangan' => $do->keterangan,
'Harga Beli' => $harga_total_beli,
'GP(Rp)' => $gp_total,
'Harga Jual' => $do->harga_penjualan,
'Margin/Kg' => $margin_kg,
'Harga Total Pembelian' => $harga_total_beli,
'Gp Total' => $gp_total,
'Normal' => $normal,
'Penjualan Akhir' => $penjualan_akhir,
'Margin Harian' => $margin_harian,
'Uang Jalan' => $do->uang_jalan,
'Uang Tangkap' => $do->uang_tangkap,
'Solar' => $do->solar,
'E-Toll' => $do->etoll,
'Total Operasional' => $total_operational,
'Laba' => $laba,
];
$totalMargin += $margin_harian;
$increment++;
}
$currentWeek = Carbon::now()->startOfWeek();
$endDate = Carbon::now()->startOfWeek()->addDays(6);
$filteredMarginData = array_filter($marginData, function ($mar) use ($currentWeek, $endDate) {
$tanggalPembelian = Carbon::parse($mar['Tanggal Pembelian']);
return $tanggalPembelian->between($currentWeek, $endDate);
});
return view('admin.dashboard',compact('marginData','filteredMarginData','Ap','Ar','totalMargin','totalDo','margin_harian','chartData'));
}
}
|
<?php
namespace madxartwork;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* madxartwork box shadow control.
*
* A base control for creating box shadows control. Displays input fields for
* horizontal shadow, vertical shadow, shadow blur, shadow spread and shadow
* color.
*
* @since 1.0.0
*/
class Control_Box_Shadow extends Control_Base_Multiple {
/**
* Get box shadow control type.
*
* Retrieve the control type, in this case `box_shadow`.
*
* @since 1.0.0
* @access public
*
* @return string Control type.
*/
public function get_type() {
return 'box_shadow';
}
/**
* Get box shadow control default value.
*
* Retrieve the default value of the box shadow control. Used to return the
* default values while initializing the box shadow control.
*
* @since 1.0.0
* @access public
*
* @return array Control default value.
*/
public function get_default_value() {
return [
'horizontal' => 0,
'vertical' => 0,
'blur' => 10,
'spread' => 0,
'color' => 'rgba(0,0,0,0.5)',
];
}
/**
* Get box shadow control sliders.
*
* Retrieve the sliders of the box shadow control. Sliders are used while
* rendering the control output in the editor.
*
* @since 1.0.0
* @access public
*
* @return array Control sliders.
*/
public function get_sliders() {
return [
'horizontal' => [
'label' => __( 'Horizontal', 'madxartwork' ),
'min' => -100,
'max' => 100,
],
'vertical' => [
'label' => __( 'Vertical', 'madxartwork' ),
'min' => -100,
'max' => 100,
],
'blur' => [
'label' => __( 'Blur', 'madxartwork' ),
'min' => 0,
'max' => 100,
],
'spread' => [
'label' => __( 'Spread', 'madxartwork' ),
'min' => -100,
'max' => 100,
],
];
}
/**
* Render box shadow control output in the editor.
*
* Used to generate the control HTML in the editor using Underscore JS
* template. The variables for the class are available using `data` JS
* object.
*
* @since 1.0.0
* @access public
*/
public function content_template() {
?>
<#
var defaultColorValue = '';
if ( data.default.color ) {
defaultColorValue = ' data-default-color=' + data.default.color; // Quotes added automatically.
}
#>
<div class="madxartwork-control-field">
<label class="madxartwork-control-title"><?php echo __( 'Color', 'madxartwork' ); ?></label>
<div class="madxartwork-control-input-wrapper">
<input data-setting="color" class="madxartwork-shadow-color-picker" type="text" placeholder="<?php echo esc_attr( 'Hex/rgba', 'madxartwork' ); ?>" data-alpha="true"{{{ defaultColorValue }}} />
</div>
</div>
<?php
foreach ( $this->get_sliders() as $slider_name => $slider ) :
$control_uid = $this->get_control_uid( $slider_name );
?>
<div class="madxartwork-shadow-slider madxartwork-control-type-slider">
<label for="<?php echo esc_attr( $control_uid ); ?>" class="madxartwork-control-title"><?php echo $slider['label']; ?></label>
<div class="madxartwork-control-input-wrapper">
<div class="madxartwork-slider" data-input="<?php echo esc_attr( $slider_name ); ?>"></div>
<div class="madxartwork-slider-input">
<input id="<?php echo esc_attr( $control_uid ); ?>" type="number" min="<?php echo esc_attr( $slider['min'] ); ?>" max="<?php echo esc_attr( $slider['max'] ); ?>" data-setting="<?php echo esc_attr( $slider_name ); ?>"/>
</div>
</div>
</div>
<?php endforeach; ?>
<?php
}
}
|
import '../styles/globals.css'
import 'tailwindcss/tailwind.css'
import { ThemeProvider } from 'next-themes'
import type { AppProps } from 'next/app'
import Layout from '../comps/Layout'
import Head from 'next/head'
import { LoginStatusContextProvider } from '../context/userLogin'
import LoadingSpinner from '../comps/LoadingSpinner'
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<LoginStatusContextProvider>
<Head>
<title>Auction House | Bidding Platform</title>
<link href="https://fonts.googleapis.com/css2?family=Kdam+Thmor+Pro&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Rubik&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Barlow&display=swap" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@500&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Kanit&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed&display=swap" rel="stylesheet" />
</Head>
<ThemeProvider enableSystem={true} attribute="class">
<Layout>
<Component {...pageProps} />
</Layout>
</ThemeProvider>
</LoginStatusContextProvider>
</>
)
}
export default MyApp
|
package datastructure.sparsearray;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* SparseArray--稀疏数组
*/
@SuppressWarnings(value = "all")
public class SparseArray2 {
private static File fileInputStream;
public static void main(String[] args) {
/**
* 初始化二维数组
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 1 0 0 0 0 0 0 0 0
* 0 0 0 0 2 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0 0 0 0
*/
int[][] array = new int[11][11];//动态初始化一个二维数组
//给数组赋值有效元素
array[1][2] = 1;
array[2][4] = 2;
//遍历二维数组
System.out.println("-----------------------------遍历二维数组-----------------------------");
for (int[] row :
array) {
for (int item :
row) {
System.out.printf("%d\t", item);
}
System.out.println();
}
//将二维数组转成稀疏数组
System.out.println("-----------------------------将二维数组转成稀疏数组-----------------------------");
/*
稀疏数组的格式
11 11 2----行数 列数 有效值个数(从第二行为有效值的信息)
1 2 1----有效值的行数 有效值的列数 有效值的值
2 4 2----有效值的行数 有效值的列数 有效值的值
... 有效值的行数 有效值的列数 有效值的值
*/
//遍历二维数组 得到有效值的个数 可以确定第一行的信息以及稀疏数组的行数
int count = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (array[i][j] != 0) {//判断是否为有效值
count++;
}
}
}
//初始化一个稀疏数组
int[][] sparseArray = new int[count + 1][3];//根据获取到的有效值个数信息 动态初始化稀疏数组
//赋值稀疏数组的第一行
sparseArray[0][0] = 11; //行数
sparseArray[0][1] = 11; //列数
sparseArray[0][2] = count; //有效值个数
//赋值稀疏数组的有效值行 通过遍历二维数组的有效值给稀疏数组相应的赋值
int numRows = 1;//稀疏数组的行 从索引为1的第二行开始(有效值从第二行开始)
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (array[i][j] != 0) {//判断是否为有效值
sparseArray[numRows][0] = i;//有效值的行数
sparseArray[numRows][1] = j;//有效值的列数
sparseArray[numRows][2] = array[i][j];//有效值的值
numRows++;
}
}
}
//遍历稀疏数组
for (int[] rows :
sparseArray) {
for (int item :
rows) {
System.out.printf("%d\t", item);
}
System.out.println();
}
//将稀疏数组转成二维数组
System.out.println("-----------------------------将稀疏数组转成二维数组-----------------------------");
//创建二维数组并初始化二维数组
int[][] oldArray = new int[sparseArray[0][0]][sparseArray[0][1]];//数组的外层行数和内层列数 分别赋值为稀疏数组第一行的第一个元素和第二个元素
//根据稀疏数组有效值信息给二维数组相应的位置赋上有效值
//遍历稀疏数组除第一行后的每一行(有效值行)
for (int i = 1; i < sparseArray.length; i++) {
oldArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
//遍历二维数组
for (int[] row :
oldArray) {
for (int item :
row) {
System.out.printf("%d\t", item);
}
System.out.println();
}
//将稀疏数组储存至磁盘中
System.out.println("-----------------------------将稀疏数组储存至磁盘中-----------------------------");
sparseArrayToIo(sparseArray);
//读取磁盘中的稀疏数组数据到内存中
System.out.println("-----------------------------读取磁盘中的稀疏数组数据到内存中-----------------------------");
int[][] sparseArrayFromIo = sparseArrayFromIo("spareArray3.txt");
//遍历稀疏数组
for (int[] rows :
sparseArrayFromIo) {
for (int item :
rows) {
System.out.printf("%d\t", item);
}
System.out.println();
}
}
/*
* @Description 将稀疏数组储存至磁盘中
* @Author EddieZhang
* @Date 2022/9/10 10:44
* @Param []
* @Return void
* @Since version-1.0
*/
public static void sparseArrayToIo(int[][] sparseArray) {
FileOutputStream fileOutputStream = null;
try {
//指定要储存到的文件
File file = new File("spareArray3.txt");
if (!file.exists()) {
file.createNewFile();
}
//造流
fileOutputStream = new FileOutputStream(file);
//将数据写入到流中
for (int i = 0; i < sparseArray.length; i++) {
for (int j = 0; j < 3; j++) {
fileOutputStream.write(sparseArray[i][j]);
}
}
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放资源
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* @Description 读取磁盘中的稀疏数组数据到内存中--(使用map集合来接收)
* @Author EddieZhang
* @Date 2022/9/10 10:54
* @Param [file]
* @Return int[][]
* @Since version-1.0
*/
public static int[][] sparseArrayFromIo(String path) {
FileInputStream fileInputStream = null;
try {
//指定要读取的文件
File file = new File(path);
//造流
fileInputStream = new FileInputStream(file);
//定义一个map集合用来储存读取到的数据
Map<Integer,Integer> map = new HashMap<>();
//定义两个变量 分别表示key和value
int k = 0;
int v = 0;
while((v = fileInputStream.read()) != -1){
map.put(k,v);
k++;
}
//此时map集合中储存了稀疏数组
//创建一个二维数组 将map集合中的数据赋值给二维数组
int index = 0;
int [][] sparseArray = new int[map.size() / 3][3];
for (int i = 0; i < map.size() / 3; i++) {
for (int j = 0; j < 3; j++) {
sparseArray[i][j] = map.get(index);
index++;
}
}
return sparseArray;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fileInputStream != null){
//释放资源
try {
fileInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
|
import requests
import json
from tkinter import *
root = Tk()
root.geometry("570x500")
root.title("Weather App")
lat = StringVar()
lat.set("")
lon = StringVar()
lon.set("")
def insert_text(text):
test_widget.insert(END, text)
def clear_text():
test_widget.delete("1.0", "end")
def weekly_forecast(lat, lon):
clear_text()
weather = requests.get(f"https://api.weather.gov/points/{lat},{lon}")
json = weather.json()
forecast = json["properties"]["forecast"]
daily_forecast = requests.get(forecast).json()
for section in daily_forecast["properties"]["periods"]:
day = section["name"]
temp = section["temperature"]
detail = section["detailedForecast"]
insert_text(f"{day}: {temp} \n")
def city_choice():
choice=city_select.get()
lat_lon=city_latlon[choice]
lat.set(lat_lon[0])
lon.set(lat_lon[1])
weekly_forecast(lat.get(),lon.get())
city_select = StringVar()
city_select.set("Select a City")
city_list = ["Binghamton", "New York", "Chicago", "Atlanta", "Denver"]
city_latlon = {"Binghamton": ["42.09", "-75.91"],
"New York": ["40.78", "-73.96"],
"Chicago": ["41.98", "-87.9"],
"Atlanta": ["33.66", "-84.42"],
"Denver": ["39.87", "-104.67"]}
'''
label_lat = Label(root, text="Enter Latitude")
entry_lat = Entry(root, width=35, borderwidth=5, textvariable=lat)
label_lon = Label(root, text="Enter Longitude")
entry_lon = Entry(root, width=35, borderwidth=5, textvariable=lon)
forecast_button = Button(root, font = 24, text = "Get Forecast",
command=lambda: weekly_forecast(lat.get(), lon.get()))
close_button = Button(root, font = 24, text = "Close Window",
command=root.destroy)
dropdown = OptionMenu(root, city_select, *city_latlon)
choose_button = Button(root, text="Select", command=city_choice)
test_widget = Text(root, font = ("Helvitica", "16"),
height=10, width=25)
dropdown.pack(pady=20)
label_lat.pack()
entry_lat.pack()
label_lon.pack()
entry_lon.pack()
choose_button.pack(pady=10)
forecast_button.pack(pady=10)
test_widget.pack()
close_button.pack(pady=10)
'''
entry_frame = Frame(root)
entry_frame.grid(row=0, column=0)
drop_frame = Frame(root)
drop_frame.grid(row=0, column=1)
label_lat = Label(entry_frame , text="Enter Latitude").pack()
entry_lat = Entry(entry_frame , width=35, borderwidth=5, textvariable=lat).pack()
label_lon = Label(entry_frame , text="Enter Longitude").pack()
entry_lon = Entry(entry_frame , width=35, borderwidth=5, textvariable=lon).pack()
button = Button(entry_frame , font = 24, text = "Get Forecast",
command=lambda: weekly_forecast(lat.get(), lon.get()))
button.pack(pady = 20)
drop_label = Label(drop_frame, text="You can also select a city:").pack()
dropdown = OptionMenu(drop_frame, city_select, *city_list).pack()
choose_button = Button(drop_frame, text="Select City", command=city_choice)
choose_button.pack(pady = 20)
weather_text = Text(root, height=16)
weather_text.grid(columnspan=2)
button2 = Button(root, font = 24, text = "Close Window",
command=root.destroy)
button2.grid(columnspan=2, pady = 20)
root.mainloop()
|
import { Service } from 'typedi';
import { DB } from '@database';
import { CreateOrderDto, UpdateOrderDto } from '@/dtos/orders.dto';
import { HttpException } from '@/exceptions/httpException';
import { Order } from '@interfaces/orders.interface';
import { OrderItem } from '@/interfaces/order-items.interface';
@Service()
export class OrderService {
public async isOrderBelongsToUser(orderId: number, userId: number): Promise<boolean> {
const order: Order = await DB.Order.findByPk(orderId);
if (!order) throw new HttpException(409, "Order doesn't exist");
return order.userId === userId;
}
public async findAllOrders(): Promise<Order[]> {
const allOrders: Order[] = await DB.Order.findAll({
include: [DB.OrderItem],
// attributes: { exclude: ['userId'] },
});
return allOrders;
}
public async findAllOrdersByUserId(userId: number): Promise<Order[]> {
const allOrders: Order[] = await DB.Order.findAll({
where: {
userId,
},
include: [DB.OrderItem],
});
return allOrders;
}
public async findOrderById(orderId: number): Promise<Order> {
const findOrder: Order = await DB.Order.findByPk(orderId);
if (!findOrder) throw new HttpException(409, "Order doesn't exist");
return findOrder;
}
public async createOrder(dto: CreateOrderDto, userId: number): Promise<Order> {
const t = await DB.sequelize.transaction();
try {
const { products, ...rest } = dto;
const createdOrder: Order = await DB.Order.create(
{
...rest,
userId,
},
{ transaction: t },
);
const orderItems: OrderItem[] = await Promise.all(
products.map(async item => {
const product = await DB.Product.findByPk(item.productId, {
transaction: t,
});
await product.decrement('inventory', { by: item.quantity, transaction: t });
await product.increment('sold', { by: item.quantity, transaction: t });
return {
productId: item.productId,
orderId: createdOrder.id,
quantity: item.quantity,
sumPrice: item.quantity * product.price,
};
}),
);
await DB.OrderItem.bulkCreate(orderItems, { transaction: t });
await t.commit();
return createdOrder;
} catch (error) {
await t.rollback();
console.log(error);
throw error;
}
}
public async updateOrder(orderId: number, dto: UpdateOrderDto): Promise<Order> {
const findOrder: Order = await DB.Order.findByPk(orderId);
if (!findOrder) throw new HttpException(409, "Order doesn't exist");
await DB.Order.update(dto, { where: { id: orderId } });
const updatedOrder: Order = await DB.Order.findByPk(orderId);
return updatedOrder;
}
// public async deleteOrder(orderId: number): Promise<Order> {
// const findOrder: Order = await DB.Order.findByPk(orderId);
// if (!findOrder) throw new HttpException(409, "Order doesn't exist");
// await DB.Order.destroy({ where: { id: orderId } });
// return findOrder;
// }
public async deleteOrder(orderId: number): Promise<void> {
try {
const findOrder: Order = await DB.Order.findByPk(orderId);
if (!findOrder) {
throw new Error(`Order with ID ${orderId} not found.`);
}
await DB.sequelize.transaction(async t => {
const orderItems = await DB.OrderItem.findAll({
where: {
orderId: findOrder.id,
},
transaction: t,
});
await Promise.all(
orderItems.map(async orderItem => {
const product = await DB.Product.findByPk(orderItem.productId, {
transaction: t,
});
await product.increment('inventory', {
by: orderItem.quantity,
transaction: t,
});
await product.decrement('sold', {
by: orderItem.quantity,
transaction: t,
});
}),
);
await DB.OrderItem.destroy({
where: {
orderId: findOrder.id,
},
transaction: t,
});
await DB.Order.destroy({ where: { id: orderId } });
return findOrder;
});
} catch (error) {
console.log(error);
throw error;
}
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('villages', function (Blueprint $table) {
$table->id();
$table->string('village_name')->nullable();
$table->unsignedBigInteger('vcdc_id')->nullable();
$table->timestamps();
$table->foreign('vcdc_id')->references('id')->on('village_council_development_committees')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('villages');
}
};
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<link rel="icon" href="favicon.ico" sizes="any">
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<title>Les Petits Douces</title>
<!-- Font Awesome icons (free version)-->
<script src="https://use.fontawesome.com/releases/v6.1.2/js/all.js" crossorigin="anonymous"></script>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous" />
<link rel="stylesheet" href="css/styles.css" />
</head>
<body id="page-top" class="d-flex flex-column h-100">
<!-- Navigation-->
<nav class="navbar navbar-expand-lg" id="mainNav">
<div class="container">
<a class="navbar-brand link-light" href="/02 - HTML/"><img alt="logo" src="images/logo.png" height="40"> Les Petits Douces</a>
<button class="navbar-toggler font-weight-bold text-white rounded" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menú
<i class="fas fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ms-auto">
<li class="nav-item mx-0 mx-lg-1">
<a class="nav-link py-1 px-0 px-lg-3 rounded link-light" href="index.html">Pasteles</a>
</li>
<li class="nav-item mx-0 mx-lg-1">
<a class="nav-link py-1 px-0 px-lg-3 rounded link-light" href="#personalizar">Personalizar Pastel</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Masthead-->
<header class="bg-secondary d-flex align-items-center masthead text-white text-center">
<div class="container">
<div class="row">
<div class="col-12">
<h1>Les Petits Douces</h1>
<p>Dulces placeres para toda la familia</p>
</div>
</div>
</div>
</header>
<main id="main" class="mt-2">
<!-- Personalización Section-->
<section class="page-section " id="personalizar">
<div class="container">
<div class="row">
<div class="col-lg-12 mb-2">
<form>
<div class="select">
<label id="pastel_label" for="pastel"><h2>¿Cuál es su pastel preferido?</h2></label>
<div class="input-group mb-3">
<select id="pastel" name="pastel" class="form-select" aria-label="">
<option value="1">Torta de Chocolate</option>
<option value="2">Torta de Fresas</option>
<option value="3">Torta de Pascua</option>
<option value="4">Torta de Queso</option>
<option value="5">Torta de Zanahoria</option>
<option value="6">Torta de Manzana</option>
</select>
</div>
</div>
<label>¿Desea combinar su pastel?</label>
<div class="form-check mb-3">
<input name="otroPastel" type="radio" class="form-check-input" value="Si" />
<label class="form-check-label" for="otroPastel">Si</label>
</div>
<div class="form-check mb-3">
<input name="otroPastel" type="radio" class="form-check-input" value="No" />
<label class="form-check-label" for="otroPastel">No</label>
</div>
<div class="select">
<label id="segundaOpción_label" for="segundaOpción"><h2>¿Con qué pastel desea combinar el pastel?</h2></label>
<div class="input-group mb-3">
<select id="segundaOpción" name="segundaOpción" class="form-control form-select" aria-label="">
<option value="1">Torta de Chocolate</option>
<option value="2">Torta de Fresas</option>
<option value="3">Torta de Pascua</option>
<option value="4">Torta de Queso</option>
<option value="5">Torta de Zanahoria</option>
<option value="6">Torta de Manzana</option>
</select>
</div>
</div>
<div class="select">
<label id="adornos_label" for="adornos"><h2>¿Qué adornos prefiere?</h2></label>
<div class="input-group mb-3">
<select id="adornos" name="adornos" class="form-control form-select" aria-label="">
<option value="1">Mensaje Personalizado - $50 c/letra</option>
<option value="2">Chispas de chocolate $1.000/gramo</option>
<option value="3">Imagen</option>
</select>
</div>
</div>
<div class="mb-3">
<label id="mensajePersonalizado_label" for="mensajePersonalizado">Redacte su mensaje personalizado</label>
<input id="mensajePersonalizado" name="mensajePersonalizado" type="text" class="form-control" />
</div>
<div class="mb-3">
<label id="chispas_label" for="chispas">¿Cuántos gramos de chispas desea?</label>
<input id="chispas" name="chispas" type="number" class="form-control" />
</div>
<div class="file-upload">
<label for="file_upload">Adjunte la imagen que desea en su pastel</label>
<div class="custom-file">
<div class="input-group mb-3">
<input id="file_upload" name="file_upload" type="file" class="custom-file-input form-control" aria-label="File Upload" />
</div>
</div>
</div>
<div class="mb-3">
<button class="btn btn-primary" type="submit">Enviar</button>
</div>
</form>
</div>
</div>
</div>
</section>
</main>
<!-- Footer-->
<footer class="footer py-2">
<div class="container">
<div class="row text-light">
<div class="col-lg-4">
<p>Dirección: Calle 102 # 50-72
<br />Barrio: Barrios Unidos
<br />Ciudad: Bogotá - Colombia
</p>
</div>
<div class="col-lg-4">
Horarios de Atención:<br /> Lun-Sáb 8:00 a.m. - 6 p.m.
</div>
<div class="col-lg-4">
Teléfonos: 601 6352984<br />
Celular: 350 2365864</div>
</div>
<p class="text-center text-light">© 2022 gfrodriguez</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="hu"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
</head>
<body>
<nav th:fragment="header" class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#my-collapse-navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">MachineManager</a>
</div>
<div class="collapse navbar-collapse"
id="my-collapse-navbar">
<ul class="nav navbar-nav">
<li th:classappend="${currentPage == 'home' ? 'active' : ''}">
<a href="/">Kezdőlap</a>
</li>
<li class="dropdown" th:classappend="${currentPage == 'machine' ? 'active' : ''}">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">Virtuális Gépek<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="/machine/list">Géppark</a></li>
<li sec:authorize="isAuthenticated()"><a href="/machine/table">Táblázat</a></li>
<li sec:authorize="isAuthenticated()" class="divider"></li>
<li sec:authorize="isAuthenticated()"><a href="/machine/new">+ Hozzáadás</a></li>
</ul>
</li>
<li sec:authorize="isAuthenticated()" class="dropdown" th:classappend="${currentPage == 'project' ? 'active' : ''}">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">Projektek<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="/project/list">Projektek</a></li>
<li class="dropdown-submenu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Projekt csoportjai</a>
<ul class="dropdown-menu">
<li th:each="project : ${@projectService.getList()}" th:object="${project}">
<a th:href="@{/project/view/} + *{id}">
<span th:text="*{name}"></span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<li sec:authorize="isAuthenticated()" class="dropdown" th:classappend="${currentPage == 'user' ? 'active' : ''}">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">Felhasználók <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="/user/list">Összes felhasználó</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" sec:authorize="isAnonymous()">
<li>
<a href="/register"><span class="glyphicon glyphicon-user"></span> Regisztráció</a>
</li>
<li>
<a href="/login"><span class="glyphicon glyphicon-log-in"></span> Bejelentkezés</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" sec:authorize="isAuthenticated()">
<li>
<a th:href="@{/user/view/} + ${#authentication.principal.id}">
<span sec:authentication="principal.fullname">UserName</span>
(<span sec:authentication="name">UserName</span>)
</a>
</li>
<li>
<a href="javascript:{}" onclick="document.getElementById('frmlogout').submit(); return false;">Logout</a>
<form sec:authorize="isAuthenticated()" id="frmlogout" th:action="@{/logout}" method="post" class="form-inline"></form>
</li>
</ul>
</div>
</div>
</nav>
</body>
|
<template>
<div class="pagination mt-5">
<!-- Previous page -->
<button
class="changePage"
@click="previousPage"
v-if="current_page != 1"
>
<i class="fas fa-chevron-left"></i>
</button>
<button
v-for="page in pagesArray"
:key="page"
@click="changePage(page)"
:class="[{ active: current_page == page }, 'page']"
>
{{ page }}
</button>
<!-- Next page -->
<button
class="changePage"
@click="nextPage"
v-if="current_page != this.pages"
>
<i class="fas fa-chevron-right"></i>
</button>
</div>
</template>
<script>
export default {
props: {
pages: Number
},
data() {
return {
current_page: 1,
total: this.pages
}
},
methods: {
previousPage() {
this.current_page -= 1
//Do something
this.$emit('updatePage', this.current_page)
},
nextPage() {
this.current_page += 1
//Do something
this.$emit('updatePage', this.current_page)
},
changePage(page) {
this.current_page = page
//Do something
this.$emit('updatePage', this.current_page)
}
},
computed: {
pagesArray() {
var pagesArr = []
var first
var last
if (this.pages > 5) {
if (this.current_page == 1) {
// First
first = 1
last = 5
} else if (this.current_page == 2) {
//Second
first = 2
last = 6
} else if (this.current_page == this.total) {
// Last
first = this.current_page - 4
last = this.current_page
} else if (this.current_page == this.total - 1) {
// Second to last
first = this.current_page - 3
last = this.current_page + 1
} else {
// Rest
first = this.current_page - 2
last = this.current_page + 2
}
} else {
//Less than 5 pages
first = 1
last = this.pages
}
for (let i = first; i <= last; i++) {
pagesArr.push(i)
}
return pagesArr
}
}
}
</script>
<style lang="scss">
@import '@/sass/variables.scss';
.pagination {
display: flex;
justify-content: center;
button {
border-radius: 5px;
border: 1px solid #e0e0e0;
color: $purple;
height: 30px;
width: 30px;
text-align: center;
margin: 0 4px;
&:hover {
background: $light_pink;
border: 1px solid $light_pink;
color: white;
}
&:focus {
outline: none;
}
}
.changePage {
i {
margin-top: 5px;
}
}
.page {
font-size: 14px;
&.active {
border: 1px solid $pink;
color: white;
background: $pink;
box-shadow: 0px 0px 3px 0px #c06c84;
}
}
}
</style>
|
#
# (C) Tenable Network Security, Inc.
#
include("compat.inc");
if (description)
{
script_id(21118);
script_version("$Revision: 1.16 $");
script_cvs_date("$Date: 2011/04/20 01:55:04 $");
script_cve_id("CVE-2006-1338");
script_bugtraq_id(17161);
script_osvdb_id(24014);
script_name(english:"MailEnable Webmail Malformed Encoded Quoted-printable Email DoS (CVE-2006-1338)");
script_summary(english:"Checks version of MailEnable");
script_set_attribute(attribute:"synopsis", value:
"The remote web server is affected by a denial of service issue." );
script_set_attribute(attribute:"description", value:
"The remote host is running MailEnable, a commercial mail server for
Windows.
According to its banner, using the webmail service bundled with the
version of MailEnable Enterprise Edition on the remote host to view
specially-formatted quoted-printable messages reportedly can result in
100% CPU utilization." );
script_set_attribute(attribute:"see_also", value:"http://www.mailenable.com/professionalhistory.asp" );
script_set_attribute(attribute:"see_also", value:"http://www.mailenable.com/enterprisehistory.asp" );
script_set_attribute(attribute:"solution", value:
"Upgrade to MailEnable Professional Edition 1.73 / Enterprise Edition
1.21 or later." );
script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:N/I:N/A:P");
script_set_cvss_temporal_vector("CVSS2#E:F/RL:U/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available");
script_set_attribute(attribute:"exploit_available", value:"true");
script_set_attribute(attribute:"plugin_publication_date", value: "2006/03/22");
script_set_attribute(attribute:"vuln_publication_date", value: "2006/03/20");
script_set_attribute(attribute:"plugin_type", value:"remote");
script_set_attribute(attribute:"cpe", value:"cpe:/a:mailenable:mailenable");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_family(english:"Windows");
script_copyright(english:"This script is Copyright (C) 2006-2011 Tenable Network Security, Inc.");
script_dependencies("smtpserver_detect.nasl", "http_version.nasl");
script_require_ports("Services/smtp", 25, "Services/www", 8080);
exit(0);
}
include("global_settings.inc");
include("misc_func.inc");
include("http.inc");
include("smtp_func.inc");
port = get_http_port(default:8080, embedded: 1);
# Make sure banner's from MailEnable.
banner = get_http_banner(port:port);
if (!banner) exit(1, "No HTTP banner on port "+port);
if (!egrep(pattern:"^Server: .*MailEnable", string:banner))
exit(0, "MailEnable is not running on port "+port);
# Check the version number from the SMTP server's banner.
smtp_port = get_kb_item("Services/smtp");
if (!smtp_port) smtp_port = 25;
if (!get_port_state(smtp_port)) exit(0, "Port "+smtp_port+" is closed");
if (get_kb_item('SMTP/'+smtp_port+'/broken')) exit(0, "MTA on port "+smtp_port+" is broken");
banner = get_smtp_banner(port:smtp_port);
if (! banner) exit(1, "No SMTP banner on port "+smtp_port);
if (banner !~ "Mail(Enable| Enable SMTP) Service") exit(0, "MailEnable is not running on port "+smtp_port);
# nb: Standard Edition seems to format version as "1.71--" (for 1.71),
# Professional Edition formats it like "0-1.2-" (for 1.2), and
# Enterprise Edition formats it like "0--1.1" (for 1.1).
ver = eregmatch(pattern:"Version: (0-+)?([0-9][^- ]+)-*", string:banner);
if (!isnull(ver))
{
if (ver[1] == NULL) edition = "Standard";
else if (ver[1] == "0-") edition = "Professional";
else if (ver[1] == "0--") edition = "Enterprise";
}
if (isnull(ver) || isnull(edition)) exit(1);
ver = ver[2];
# nb: Professional versions < 1.73 are vulnerable.
if (edition == "Professional")
{
if (ver =~ "^1\.([0-6]|7($|[0-2]))") security_warning(port);
}
# nb: Enterprise Edition versions < 1.21 are vulnerable.
else if (edition == "Enterprise")
{
if (ver =~ "^1\.([01]([^0-9]|$)|2$)") security_warning(port);
}
|
<template>
<div class="task-list-container pt-2 pb-2">
<b-list-group class="mb-2">
<b-list-group-item v-if="tasks.length === 0">
No tasks!
</b-list-group-item>
<Task
v-for="(task, i) in tasks"
:key="`task${i}_${task.name}`"
:task="task"
:idx="i"
role="button"
tabindex="0"
/>
</b-list-group>
<b-button
@click="createTask"
v-b-modal.task-modal
variant="primary"
class="text-dark"
>
Add Task
</b-button>
</div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import Task from "./Task.vue";
import vxm from "@/store/index.vuex";
import UserTask from "@/types/Task";
@Component({
components: {
Task,
},
})
export default class TaskList extends Vue {
get tasks(): UserTask[] {
return this.vxm.store.tasks;
}
get vxm(): typeof vxm {
return vxm;
}
createTask() {
vxm.store.modals.task.index = -1; // No task is being edited
vxm.store.modals.task.completed = false;
}
}
</script>
<style scoped></style>
|
defmodule PragstudioLiveviewCodeWeb.LicenseLive do
use PragstudioLiveviewCodeWeb, :live_view
alias PragstudioLiveviewCode.Licenses
import Number.Currency
def mount(_params, _session, socket) do
if connected?(socket) do
:timer.send_interval(1000, self(), :tick)
end
expiration_time = Timex.shift(Timex.now(), hours: 1)
socket =
assign(socket,
seats: 3,
amount: Licenses.calculate(3),
expiration_time: expiration_time,
time_remaining: time_remaining(expiration_time)
)
{:ok, socket}
end
def render(assigns) do
~H"""
<h1>Team License</h1>
<p class="m-4 font-semibold text-indigo-800">
<%= if @time_remaining > 0 do %>
<%= format_time(@time_remaining) %> left to save 20%
<% else %>
Expired!
<% end %>
</p>
<div id="license">
<div class="card">
<div class="content">
<div class="seats">
<img src="images/license.svg">
<span>
Your license is currently for
<strong><%= @seats %></strong> <%= ngettext("seat", "seats", @seats) %>.
</span>
</div>
<form phx-change="update">
<input type="range" min="1" max="10"
name="seats" value={@seats}
phx-debounce="250" />
</form>
<div class="amount">
<%= number_to_currency(@amount) %>
</div>
</div>
</div>
</div>
"""
end
def handle_event("update", %{"seats" => seats}, socket) do
seats = String.to_integer(seats)
{:noreply,
assign(socket,
seats: seats,
amount: Licenses.calculate(seats)
)}
end
def handle_info(:tick, socket) do
expiration_time = socket.assigns.expiration_time
socket = assign(socket, time_remaining: time_remaining(expiration_time))
{:noreply, socket}
end
defp time_remaining(expiration_time) do
DateTime.diff(expiration_time, Timex.now())
end
defp format_time(time) do
time
|> Timex.Duration.from_seconds()
|> Timex.format_duration(:humanized)
end
end
|
package site.assad.springcluodnetflix.fallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* spring-cloud-producer 服务熔断行为
*
* @author yulinying
* @since 2020/11/2
*/
public class ProducerFallback implements FallbackProvider {
private final Logger logger = LoggerFactory.getLogger(FallbackProvider.class);
/**
* 指定处理路由
*/
@Override
public String getRoute() {
return "spring-cloud-producer";
}
/**
* 熔断 fallback 逻辑
*/
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
if (cause != null && cause.getCause() != null) {
String reason = cause.getCause().getMessage();
logger.info("Excption {}",reason);
}
return fallback();
}
private ClientHttpResponse fallback(){
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return 200;
}
@Override
public String getStatusText() throws IOException {
return "OK";
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream("The service is unavailable.".getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
}
|
package problem3;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class PerishableFoodItemTest {
private PerishableFoodItem item;
@Before
public void setUp() {
item = new PerishableFoodItem("Perishable",
34.5,
90,
10,
40);
}
@Test
public void testConstructorAndGetters() {
assertEquals(10, (int) item.getOrderDate());
assertEquals(40, (int) item.getExpirationDate());
// Zero order date
item = new PerishableFoodItem("Perishable",
34.5,
90,
0,
1);
assertEquals(0, (int) item.getOrderDate());
assertEquals(1, (int) item.getExpirationDate());
// Negative order date, zero exp. date
// Negatives allowed in the event that something was ordered prior to
// deploying this system.
item = new PerishableFoodItem("Perishable",
34.5,
90,
-1,
0);
assertEquals(-1, (int) item.getOrderDate());
assertEquals(0, (int) item.getExpirationDate());
}
@Test(expected = IllegalArgumentException.class)
public void testOrderLessThanExpiration() {
PerishableFoodItem item = new PerishableFoodItem("Perishable",
34.5,
90,
10,
9);
}
@Test(expected = IllegalArgumentException.class)
public void testOrderEqualToExpiration() {
PerishableFoodItem item = new PerishableFoodItem("Perishable",
34.5,
90,
10,
10);
}
@Test(expected = IllegalArgumentException.class)
public void testTooManyItems() {
PerishableFoodItem item = new PerishableFoodItem("Perishable",
34.5,
101,
10,
10);
}
@Test
public void toString1() {
String expected = "'Perishable', $34.50/unit, 90 in stock, ordered on day 10, expires on day 40";
assertEquals(expected, item.toString());
}
@Test
public void equals1() {
PerishableFoodItem item2 = new PerishableFoodItem("Perishable",
34.5,
90,
10,
40);
assertEquals(item, item2);
item2 = new PerishableFoodItem("Perishable",
34.5,
90,
0,
40);
assertNotEquals(item, item2);
item2 = new PerishableFoodItem("Perishable",
34.5,
90,
10,
45);
assertNotEquals(item, item2);
}
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Server-side Pagination and Sorting for Dynamic Data</title>
<style type="text/css">
/*
margin and padding on body element
can introduce errors in determining
element position and are not recommended;
we turn them off as a foundation for YUI
CSS treatments.
*/
body {
margin: 0;
padding: 0;
}
</style>
<link rel="stylesheet" type="text/css"
href="${resource(plugin: 'yui', dir: 'js/yui/fonts', file: 'fonts-min.css')}"/>
<link rel="stylesheet" type="text/css"
href="${resource(plugin: 'yui', dir: 'js/yui/paginator/assets/skins/sam', file: 'paginator.css')}"/>
<link rel="stylesheet" type="text/css"
href="${resource(plugin: 'yui', dir: 'js/yui/datatable/assets/skins/sam', file: 'datatable.css')}"/>
<g:javascript plugin="yui" src="js/yui/yahoo-dom-event/yahoo-dom-event.js"/>
<g:javascript plugin="yui" src="js/yui/connection/connection-min.js"/>
<g:javascript plugin="yui" src="js/yui/json/json-min.js"/>
<g:javascript plugin="yui" src="js/yui/element/element-min.js"/>
<g:javascript plugin="yui" src="js/yui/paginator/paginator-min.js"/>
<g:javascript plugin="yui" src="js/yui/datasource/datasource-min.js"/>
<g:javascript plugin="yui" src="js/yui/datatable/datatable-min.js"/>
<!--there is no custom header content for this example-->
</head>
<body class=" yui-skin-sam">
<h1>Server-side Pagination and Sorting for Dynamic Data</h1>
<div class="exampleIntro">
<p>This example enables server-side sorting and pagination for data that is
dynamic in nature.</p>
</div>
<div id="dynamicdata"></div>
<script type="text/javascript">
YAHOO.example.DynamicData = function()
{
// Column definitions
var myColumnDefs = [
// sortable:true enables sorting
{
key:"id",
label:"ID",
sortable:true
},
{
key:"name",
label:"Name",
sortable:true
},
{
key:"date",
label:"Date",
sortable:true,
formatter:"date"
},
{
key:"price",
label:"Price",
sortable:true
},
{
key:"number",
label:"Number",
sortable:true
}
];
// Custom parser
var stringToDate = function( sData )
{
var array = sData.split( "-" );
return new Date( array[1] + " " + array[0] + ", " + array[2] );
};
// DataSource instance
var myDataSource = new YAHOO.util.DataSource( "/omar-2.0/yuiTableTest/getData?" );
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {
resultsList: "records",
fields: [
{
key:"id",
parser:"number"
},
{
key:"name"
},
{
key:"date",
parser:stringToDate
},
{
key:"price",
parser:"number"
},
{
key:"number",
parser:"number"
}
],
metaFields: {
totalRecords: "totalRecords" // Access to value in the server response
}
};
// DataTable configuration
var myConfigs = {
initialRequest: "sort=id&dir=asc&startIndex=0&results=25", // Initial request for first page of data
dynamicData: true, // Enables dynamic server-driven data
sortedBy : {key:"id", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
paginator: new YAHOO.widget.Paginator( { rowsPerPage:25 } ) // Enables pagination
};
// DataTable instance
var myDataTable = new YAHOO.widget.DataTable( "dynamicdata", myColumnDefs, myDataSource, myConfigs );
// Update totalRecords on the fly wit
// h value from server
myDataTable.handleDataReturnPayload = function( oRequest, oResponse, oPayload )
{
oPayload.totalRecords = oResponse.meta.totalRecords;
return oPayload;
}
return {
ds: myDataSource,
dt: myDataTable
};
}();
</script>
</body>
</html>
|
import { useEffect, useState } from "react";
// Interfaces
import IShorterProps from "../../shared/interfaces/shorter";
// Components
import Card from "../../components/Card";
import CardList from "./CardList";
import FormShorterLinks from "../../components/FormShorterLinks";
import LinkButton from "../../components/LinkButton";
// Styles
import {
Banner,
BannerFooter,
ControlBanner,
SectionCustom,
SectionShorter
} from "./styles";
//Json file with the information inside the cards
import db from "./db.json";
const baseURL = "https://api.shrtco.de/v2/";
export default function Home() {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [listShorter, setListShorter] = useState<IShorterProps[]>(() => {
const shortLinksList = localStorage.getItem("@shortening-app:list");
if (shortLinksList === null) {
return [];
} else {
return JSON.parse(shortLinksList);
}
});
function handleOnSubmit(url: string) {
try {
setIsLoading(true);
setTimeout(async () => {
const response = await fetch(`${baseURL}shorten?url=${url}`);
const data = await response.json();
if (response.ok) {
setIsLoading(false);
setListShorter(prev => [...prev, data.result]);
localStorage.setItem("@shortening-app:list", JSON.stringify([...listShorter, data.result]));
}
if (response.status === 400) {
setIsLoading(false);
throw new Error(`Ocorreu Bad Request - ${response.status}`);
}
if (response.status === 404) {
setIsLoading(false);
throw new Error(`Not Found - ${response.status}`);
}
}, 1000);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
listShorter.reverse();
}, [listShorter]);
return (
<>
<Banner>
<div className="container">
<ControlBanner>
<h1>
More than just
<br />
shorter links
</h1>
<p>
Build your brand’s recognition and get detailed insights
<br />
on how your links are performing.
</p>
<div>
<LinkButton to="#">
Get Started
</LinkButton>
</div>
</ControlBanner>
<div className="image-background"></div>
</div>
</Banner>
<SectionShorter>
<div className="container-form">
<FormShorterLinks handleOnSubmit={handleOnSubmit} isLoading={isLoading} />
</div>
{
listShorter.length !== 0
? <ul>
{listShorter.map((item, index) => (
<li key={index}>
<CardList
urlOriginal={item.original_link}
shorter={item.short_link}
/>
</li>
))}
</ul>
: ""
}
</SectionShorter>
<SectionCustom>
<div className="container">
<header>
<h2>
Advanced Statistics
</h2>
<p>
Track how your links are performing across the web with
our advanced statistics dashboard.
</p>
</header>
<div className="group-cards">
<ul>
{db.map(card => (
<li key={card.id}>
<Card
title={card.title}
description={card.description}
svg={card.svg}
/>
</li>
))}
</ul>
</div>
</div>
</SectionCustom>
<BannerFooter>
<h2>
Boost your links today
</h2>
<LinkButton to="#">
Get Started
</LinkButton>
</BannerFooter>
</>
);
}
|
// src/screens/BookListScreen.tsx
import React from 'react';
import {View, Text, Button} from 'react-native';
import {useQuery} from 'react-query';
import {getBooks} from '../services/MovieService';
import BookList from '../components/BookList';
import {useTranslation} from 'react-i18next';
const BookListScreen: React.FC = () => {
const {data: books, isLoading, isError} = useQuery('books', getBooks);
const {t, i18n} = useTranslation();
const changeLanguage = language => {
i18n.changeLanguage(language);
};
if (true) {
return (
<View>
<Text>Loading...</Text>
<Button
title="Switch to English"
onPress={() => changeLanguage('en')}
/>
<Button title="Switch to Arabic" onPress={() => changeLanguage('ar')} />
<Text>{t('welcome')}</Text>
<Text>{t('greeting', {name: 'John de'})}</Text>
</View>
);
}
if (isError) {
return (
<View>
<Text>Error loading books</Text>
</View>
);
}
return <BookList books={books} />;
};
export default BookListScreen;
|
#Deliverable 1
library(dplyr)
MechaCarMpg_data <- read.csv('MechaCar_mpg.csv') #import dataset
head(MechaCarMpg_data)
lm(mpg ~ vehicle_length+vehicle_weight+spoiler_angle+ground_clearance+AWD,MechaCarMpg_data) #create a linear model
summary(lm(mpg ~ vehicle_length+vehicle_weight+spoiler_angle+ground_clearance+AWD,MechaCarMpg_data)) #summarize linear model
#Deliverable 2
Suspension_coil <- read.csv('Suspension_Coil.csv') #import dataset
total_summary <- Suspension_coil %>% summarize(Mean=mean(PSI),Median=median(PSI),Variance=var(PSI),SD=sd(PSI), .groups = "keep")
lot_summary <- Suspension_coil %>% group_by(Manufacturing_Lot) %>% summarize(Mean=mean(PSI),Median=median(PSI),Variance=var(PSI),SD=sd(PSI), .groups = "keep")
#Deliverable 3
t.test(Suspension_coil$PSI,mu= 1500) #Across all Lots
t.test(subset(Suspension_coil,Manufacturing_Lot=="Lot1")$PSI,mu=1500) #Lot1
t.test(subset(Suspension_coil,Manufacturing_Lot=="Lot2")$PSI,mu=1500) #Lot2
t.test(subset(Suspension_coil,Manufacturing_Lot=="Lot3")$PSI,mu=1500) #Lot3
|
import { useParams } from "react-router-dom"
import { useEffect, useState } from "react"
import { IoIosArrowBack } from 'react-icons/io'
import { getPokeData, getAbilityDesc } from "../../services/poke-individual"
import { ClipLoader } from "react-spinners"
import { useContext } from "react"
import { ThemeeContext } from "../../contexts/theme-context"
import {
Section,
CardDiv,
Img,
Ul,
ContainerUl,
P,
H2,
H3,
MiniContainerList,
DescP,
BackLink,
MovesP
} from './styled'
export const PokeData = () => {
const [poke, setPoke] = useState()
const [pokeMoves, setPokeMoves] = useState([])
const [pokeAbilities, setPokeAbilities] = useState([])
const [isLoading, setIsLoading] = useState(true)
const [abilityUrls, setAbilityUrls] = useState([])
const [abilityDesc, setAbilityDesc] = useState([])
const { id } = useParams()
const { theme } = useContext(ThemeeContext)
const urlGif = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/showdown/${id}.gif`
useEffect(() => {
getPokeData(id, setPoke, setAbilityUrls, setPokeAbilities, setPokeMoves, setIsLoading)
getAbilityDesc(abilityUrls, setAbilityDesc)
// eslint-disable-next-line
}, [isLoading])
const getTypes = () => {
const pokemonTypes = poke.types
return (pokemonTypes[1]) ? pokemonTypes[0].type.name.toUpperCase() + " / " + pokemonTypes[1].type.name.toUpperCase() : pokemonTypes[0].type.name.toUpperCase()
}
const RenderList = () => (
<>
{isLoading ? (
<div style={{ marginTop: '40px' }}><ClipLoader color={ theme.color3 }/></div>
) : (
<CardDiv>
<P>{getTypes()}</P>
<Img src={urlGif} alt={poke.name}></Img>
<H2>{poke.name.toUpperCase()}</H2>
<ContainerUl>
<MiniContainerList>
<H3>MOVES</H3>
<Ul>
{poke && pokeMoves.map((item, index) => (
<li key={index}>
<MovesP>{item.move.name.toUpperCase()}</MovesP>
</li>
))}
</Ul>
</MiniContainerList>
<MiniContainerList>
<H3>ABILITIES</H3>
<Ul>
{poke && pokeAbilities.map((item, index) => (
<li key={index}>
<H3>{item.ability.name.toUpperCase()}</H3>
<DescP>{abilityDesc[index]}</DescP>
</li>
))}
</Ul>
</MiniContainerList>
</ContainerUl>
</CardDiv>
)
}
</>
)
return (
<>
<BackLink to="/"><IoIosArrowBack /></BackLink>
<Section>
{RenderList()}
</Section>
</>
)
}
|
# Q1. 인덱스에 정규표현식을 쓸 수 있는지?
# A1. 와일드 카드를 제외한 정규표현식 사용 불가
POST test1
{
"test": "TTT"
}
POST test2
{
"test": "TTT"
}
DELETE test[0-9]
DELETE test*
# Q2. 클러스터 샤드 라우팅 primaries, new_primaries 의 차이
# A2. 상황별로 정리
# 각 모드별로 클러스터 내에 노드가 모두 있을 때
# [인덱스 추가]
# primaries - 모든 노드에 새롭게 추가되는 인덱스에 대해서만 프라이머리 샤드만 추가, 레플리카는 unassigned
# new_primaries - 모든 노드에 새롭게 추가되는 인덱스에 대해서만 프라이머리 샤드>만 추가, 레플리카는 unassigned
# -> 동일
#
# 각 모드별로 클러스터에 노드를 추가할 때
# [샤드 배치]
# primaries - 투입되면 프라이머리 샤드들을 새롭게 추가된 노드에게 배치
# new_primaries - 투입되면 샤드를 받지 않은 채로 노드만 추가됨
# [인덱스 추가]
# primaries - 모든 노드에 새롭게 추가되는 인덱스에 대해서만 프라이머리 샤드만 추가, 레플리카는 unassigned
# new_primaries - 새롭게 추가된 노드에만 프라이머리 샤드들을 배치
PUT _all/_settings
{
"settings": {
"index.unassigned.node_left.delayed_timeout": "5s"
}
}
GET _cluster/settings
PUT _cluster/settings
{
"transient" : {
"cluster.routing.allocation.enable" : null
}
}
PUT test1
{
"settings": {
"index.number_of_shards": 3,
"index.number_of_replicas": 1,
"index.unassigned.node_left.delayed_timeout": "5s"
}
}
# node stop
PUT _cluster/settings
{
"transient" : {
"cluster.routing.allocation.enable" : "primaries"
}
}
# node start
# 투입된 노드에 프라이머리 샤드만 할당
PUT test2
{
"settings": {
"index.number_of_shards": 3,
"index.number_of_replicas": 1,
"index.unassigned.node_left.delayed_timeout": "5s"
}
}
# 노드들에게 프라이머리 샤드만 할당
PUT _cluster/settings
{
"transient" : {
"cluster.routing.allocation.enable" : null
}
}
# node stop
PUT _cluster/settings
{
"transient" : {
"cluster.routing.allocation.enable" : "new_primaries"
}
}
# node start
# 투입된 노드에 기존 인덱스의 샤드는 할당하지 않음
PUT test3
{
"settings": {
"index.number_of_shards": 3,
"index.number_of_replicas": 1
}
}
# 새롭게 생성한 인덱스의 샤드는 모든 노드들에게 할당
# 다만, 하나의 노드에만 샤드가 분배되는 것 처럼 보이는 것은 투입된 노드가 다른 노드들에 비해 샤드가 없기 때문에 disk threshold 에 의해 그렇게 보이는 것
PUT _cluster/settings
{
"transient" : {
"cluster.routing.allocation.enable" : null
}
}
# Q3. search analyzer 는 무엇인가요?
# A. 보통의 경우 인덱스에 애널라이저를 설정하고, 특정 text field 에 해당 애널라>이저를 설정하면 색인할 때 해당 애널라이저의 방식을 따라 토큰이 생성됩니다. 이후>에 검색 시에도 동일한 애널라이저를 통해 토큰을 생성하여 일치되는 토큰이 있을 때 검색이 됩니다.
# 그런데, N-grams. Edge N-grams 같은 토커나이저들은 색인 시에 실제 사용자가 검>색하지 않을 토큰이 다량으로 생성되는 방식으로 토큰을 생성합니다.
# ex) Foxes (min, max gram 3) -> Fox, oxe, xes
# 사용자는 실제 의미있는 Fox 로 검색하는 게 일반적입니다. 그래서 색인 시에는 가>능한 많은 토큰들을 생성하고, 검색을 할 때에는 의미 있는 토큰만을 대상으로 검색하고 싶을 때 search_analyzer 를 사용합니다.
# https://www.elastic.co/guide/en/elasticsearch/reference/current/search-analyzer.html
# ngram token
PUT ngram_index
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer"
}
},
"tokenizer": {
"my_tokenizer": {
"type": "ngram",
"min_gram": 3,
"max_gram": 3,
"token_chars": [
"letter",
"digit"
]
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "my_analyzer"
}
}
}
}
POST ngram_index/_analyze
{
"analyzer": "my_analyzer",
"text": "Foxes"
}
# search_analyzer
PUT search_analyzer_index1
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer"
}
},
"tokenizer": {
"my_tokenizer": {
"type": "ngram",
"min_gram": 3,
"max_gram": 3,
"token_chars": [
"letter",
"digit"
]
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "my_analyzer",
"search_analyzer": "standard"
}
}
}
}
POST search_analyzer_index1/_doc
{
"title": "Foxes"
}
POST search_analyzer_index1/_search
{
"query": {
"match": {
"title": "Fox"
}
}
}
# lowercase token filter for standard analyzer
PUT search_analyzer_index2
{
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"tokenizer": "my_tokenizer",
"filter": [ "lowercase" ]
}
},
"tokenizer": {
"my_tokenizer": {
"type": "ngram",
"min_gram": 3,
"max_gram": 3,
"token_chars": [
"letter",
"digit"
]
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "my_analyzer",
"search_analyzer": "standard"
}
}
}
}
POST search_analyzer_index2/_doc
{
"title": "Foxes"
}
POST search_analyzer_index2/_search
{
"query": {
"match": {
"title": "Fox"
}
}
}
# Q4. 쿼리가 한 번이라도 수행되었을 때 받은 스코어를 유지할 수 있는 방법은 없나요?
# A4. constant_score 를 사용하여 처음부터 스코어를 지정해주는 방법이 있습니다. 이 쿼리는 사용자가 특정 쿼리에 스코어를 지정하여 지속적으로 사용할 것이 예상되기 때문에 filter 절 내에 정의하도록 구성되어 있습니다.
# score1, 2, 3...
POST bank/_search
{
"query": {
"match": {
"address": "Fleet"
}
}
}
GET bank/_search
{
"query": {
"constant_score" : {
"filter": {
"match" : { "address" : "Fleet"}
},
"boost" : 3.4
}
}
}
# Q5. bulk size 조정 방법
# 벌크 사이즈의 조정은 클라에서 합니다. ES 에서 조정할 수 있는 것은 bulk job 이 코어를 몇 개 까지 쓸 수 있게 할 것인지, 코어를 다 써서 더 이상 할당할 코어가 없을 때 요청된 job 들을 얼마나 저장할지만 결정합니다. 6장에 해당 내용이 있습니다.
# Q6. term 쿼리는 스코어가 일정한데 어떤 사항을 기준으로 순서가 결정되나요?
# A6. 순서는 랜덤하게 결정됩니다. 스코어가 모두 동일하기 때문에 전체 문서가 필요하면 pagination 을 활용해야 합니다.
# 8509
POST shakespeare/_search
{
"query": {
"term": {
"speaker.keyword": "CADE"
}
}
}
# Q7. search template
# A7. 사용자가 요청할 쿼리의 형식을 미리 템플릿화 하여 정의하고 정의된 템플릿에 편하게 쿼리를 요청할 수 있는 기능
GET _search/template
{
"source" : {
"query": { "match" : { "{{my_field}}" : "{{my_value}}" } },
"size" : "{{my_size}}"
},
"params" : {
"my_field" : "message",
"my_value" : "some message",
"my_size" : 5
}
}
POST _scripts/my_search_template
{
"script":{
"lang":"mustache",
"source":{
"query":{
"match":{
"text_entry":"{{my_query}}"
}
}
}
}
}
GET _scripts/my_search_template
POST shakespeare/_search/template
{
"id": "my_search_template",
"params": {
"my_query": "my mother"
}
}
DELETE _scripts/my_search_template
# Q8. 저장된 Routing Key 들은 어디서 볼 수 있나요?
# A8. Routing Key 는 문서의 ID 를 대체하여 샤드 할당 알고리즘에 의해 문서를 색인합니다.
# 문서의 ID 와 마찬가지로 별도의 리스트를 확인하기 어려운 정보로 확인됩니다.
# 해당 Key 는 특정 샤드로 데이터를 저장하고 싶을 때 사용하는 unique key 입니다.
# _source field 에서 자동으로 사용할 수 없는 항목이니 문서의 필드에 함께 추가하여 색인하는 게 좋을 것 같습니다.
# Q9. copy_to 필드는 어디에 저장되나요?
# A9. ES 공식 문서에 해당 필드는 디스크에 저장되지 않는다고 명시되어 있습니다.
# _source 필드는 디스크에 저장되는 필드입니다. 즉, copy_to 는 쿼리 타임에 메모리 상에 저장되었다가 소멸되는 것으로 보입니다.
DELETE rindex
# Routing key 를 이용한 인덱싱
POST rindex/_doc?routing=user1
{
"title": "This is a document for user1"
}
POST rindex/_doc?routing=user2
{
"title": "This is a document for user2"
}
GET rindex/_search
GET rindex/_search?routing=user1
GET rindex/_search?routing=user2
POST rindex/_search?routing=user2
{
"query": {
"match": {
"title": "user1"
}
}
}
POST rindex/_search?routing=user1
{
"query": {
"match": {
"title": "user1"
}
}
}
POST rindex/_search
{
"query": {
"terms": {
"_routing": [ "user1", "user2" ]
}
}
}
|
package com.example.myapplication.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import coil.compose.rememberImagePainter
import com.example.myapplication.R
import com.example.myapplication.data.model.StarWarsCharacter
import com.example.myapplication.ui.theme.DarkGray
import com.example.myapplication.ui.theme.StarJediFont
import com.example.myapplication.ui.theme.White
import com.example.myapplication.viewmodel.StarWarsCharacterViewModel
import kotlinx.coroutines.flow.map
@Composable
fun StarWarsCharacterListScreen(
viewModel: StarWarsCharacterViewModel,
onCharacterClick: (StarWarsCharacter) -> Unit
) {
val nonNullableCharactersFlow = remember(viewModel.characters) {
viewModel.characters.map { it ?: PagingData.empty() }
}
val characters = nonNullableCharactersFlow.collectAsLazyPagingItems()
LazyColumn(modifier = Modifier.fillMaxWidth()) {
items(characters) { character ->
character?.let {
CharacterItem(character = it, onCharacterClick = onCharacterClick)
}
}
when {
characters.loadState.append is LoadState.Loading -> {
item { LoadingItem() }
}
characters.loadState.refresh is LoadState.Loading -> {
item { FullScreenLoading() }
}
characters.loadState.refresh is LoadState.Error -> {
item { FullScreenError(onRetry = { characters.retry() }) }
}
}
}
}
@Composable
fun FullScreenLoading() {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(color = DarkGray)
}
}
@Composable
fun FullScreenError(onRetry: () -> Unit) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = stringResource(R.string.text_failed_to_load),
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = onRetry) {
Text(stringResource(R.string.text_retry))
}
}
}
}
@Composable
fun LoadingItem() {
Box(
contentAlignment = Alignment.Center, modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
CircularProgressIndicator(color = DarkGray)
}
}
@Composable
fun CharacterItem(
character: StarWarsCharacter,
onCharacterClick: (StarWarsCharacter) -> Unit
) {
val painter = rememberImagePainter(
data = character.imageUrl,
builder = {
placeholder(R.drawable.ic_placeholder)
error(R.drawable.ic_placeholder_error)
}
)
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.clickable { onCharacterClick(character) },
colors = CardDefaults.cardColors(containerColor = DarkGray),
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(DarkGray)
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.size(64.dp)
.clip(CircleShape)
.border(1.dp, White, CircleShape)
) {
Image(
painter = painter,
contentDescription = stringResource(R.string.text_star_wars_character_image),
modifier = Modifier
.fillMaxWidth(),
contentScale = ContentScale.Crop
)
}
Spacer(modifier = Modifier.width(16.dp))
Text(
text = "${character.name}, ${character.birthYear}",
style = MaterialTheme.typography.bodyLarge,
color = White,
fontFamily = StarJediFont
)
}
}
}
|
package com.medico.api.core.entity;
import com.medico.api.adapters.dto.request.DadosAtualizarMedico;
import com.medico.api.adapters.enums.EspecialidadeEnum;
import jakarta.persistence.*;
import lombok.*;
@Table(name = "medico")
@Entity(name= "Medico")
@Getter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = "id")
@Builder
public class Medico {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String nome;
String email;
String telefone;
String crm;
@Enumerated(EnumType.STRING)
EspecialidadeEnum especialidade;
@Embedded
Endereco endereco;
public void atualizarInformacoes(DadosAtualizarMedico dados) {
if (dados.nome() != null) {
this.nome = dados.nome();
}
if (dados.telefone() != null) {
this.telefone = dados.telefone();
}
if (dados.endereco() != null) {
this.endereco.atualizarInformacoes(dados.endereco());
}
}
}
|
package Learning;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CustomisedXpath {
public static WebDriverWait wait;
public static Actions act;
public static WebElement w1;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
WebDriver browser = new ChromeDriver(options);
browser.manage().timeouts().implicitlyWait(Duration.ofSeconds(6)); //5 seconds wait will be applicable for all setps
browser.get("https://mail.rediff.com/cgi-bin/login.cgi");
browser.manage().window().maximize();
//Implicit Wait
browser.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
//Explicit Wait
wait = new WebDriverWait(browser, Duration.ofSeconds(20));
//Validate that the text "username" is present for username edit box - using text() function of xpath
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//p[text() = 'Username']"), "Username"));
//Type on Username
browser.findElement(By.xpath("//*[@id='login1']")).sendKeys("selenium.testmay2017");
//Validate that the text "password" is present for password edit box
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//p[text() = 'Password']"), "Password"));
//Type on Passwords
browser.findElement(By.xpath("//*[@id='password']")).sendKeys("test@1234");
//Validate for a attribute value in Sign In button - customised with compound class for xpath
wait.until(ExpectedConditions.attributeToBe(By.xpath("//div[@class='floatL leftwidth']/div[2]/div[2]/div[2]/div[1]/input[2]"), "name", "proceed"));
//Click on sign button Customised xpath with AND or OR logic
browser.findElement(By.xpath("//input[@type = 'submit' and @value = 'Sign in']")).submit();
//Validate that "write mail" text is present
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//b[text() = 'Write mail']"), "Write mail"));
//Click on Write Mail link
//driver.findElement(By.className("rd_active")).click();
//If page does not open like in line 54, use the Actions class to simulate mouse movement and Keystrokes
//Click using Actions class
//When using actions class, use the build() method to build the simulation
//Also use the perform() method to perform the simulation
//If build() method and perform() method not used, will show error
act = new Actions(browser);
w1 = browser.findElement(By.xpath("//b[text() = 'Write mail']"));
act.moveToElement(w1).click();
act.build().perform();
//Validate that "To:" text is present
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//label[@class = 'lbl-link rd_lbl_addr_to']"), "To:"));
//Type on To field
//driver.findElement(By.xpath("//li[@id='as-original-TO_IDcmp3']/input[1]")).clear();
//driver.findElement(By.xpath("//li[@id='as-original-TO_IDcmp3']/input[1]")).sendKeys("kaushik.aryaan@gmail.com");
browser.findElement(By.xpath("//input[starts-with(@id, 'TO_IDcmp')]")).clear();
browser.findElement(By.xpath("//input[starts-with(@id, 'TO_IDcmp')]")).sendKeys("kaushik.aryaan@gmail.com");
browser.findElement(By.xpath("//input[starts-with(@id, 'TO_IDcmp')]")).sendKeys(Keys.RETURN);
//Validate that "Subject:" text is present
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//label[text() = 'Subject:']"), "Subject:"));
//Type on Subject field
browser.findElement(By.xpath("//input[contains(@class, 'rd_inp_sub rd_subject_datacmp')]")).clear();
browser.findElement(By.xpath("//input[contains(@class, 'rd_inp_sub rd_subject_datacmp')]")).sendKeys("Mail Sending Subject");
//To write in Compose area , we need to switch to frame as compose area is inside frame
//Frame is a web page embedded inside another webpage
//Selenium has focus in main page as it has opened the main page
//To work on compose area, which is inside frame, we need to switch focus from main page to frame
//frame is created by iframe tag
/*
* We can switch to frame by three methods:
*
* driver.switchTo().window(SessionID)
* a) driver.switchTo().frame(index Number) - index number starts with 0
* b) driver.switchTo().frame(id attribute value or name attribute value) - iframe's
* id attribute or name attribute
* c) driver.switchTo().frame(WebElement w) - by the address of the frame. Address
* can be kept in WebElement interface by all 8 locators)
*
*
*
*/
//Switch to the frame by address
w1 = browser.findElement(By.xpath("//iframe[@class = 'cke_wysiwyg_frame cke_reset']"));
browser.switchTo().frame(w1);
//Type on compose area after switching to frame
browser.findElement(By.xpath("/html/body")).sendKeys("Email Sending...");
//Get the focus back to main page from frame
browser.switchTo().defaultContent();
//Validate that "Send" text is present
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.linkText("Send"), "Send"));
//Click on Send link
browser.findElement(By.linkText("Send")).click();
//Validate that "Logout" text is present
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.linkText("Logout"), "Logout"));
//Click on Logout link
browser.findElement(By.partialLinkText("out")).click();
//Close the app
//browser.quit();
}
}
|
import React from 'react'
import {useForm} from 'react-hook-form'
import { useDispatch } from 'react-redux';
import {setSignUpData} from '../../../slices/authSlice'
import {sendOpt} from '../../../services/operations/authAPI'
import { useNavigate } from 'react-router-dom';
const SignUpForm = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const {
register,
handleSubmit,
formState:{errors}
} = useForm();
// sign up handler
const submitSignUp = (data) => {
dispatch(setSignUpData(data));
const email = data.email;
sendOpt(email, navigate);
}
return (
<div className='flex flex-col gap-8' >
<h3 className='text-[#FFFFFF] font-semibold text-3xl ' >Sign Up</h3>
<form
onSubmit={handleSubmit(submitSignUp)}
className='flex flex-col gap-4 '
>
{/* full name */}
<label>
<input
type="text"
placeholder='Full Name'
{...register("fullName", {required:true})}
className='bg-[#333333] px-5 py-3 rounded outline-none text-white w-full'
/>
{/* error */}
{
errors.fullName && (
<p className='text-[#E87C08] text-sm ' >Please enter full name</p>
)
}
</label>
{/* email */}
<label>
<input
type="email"
placeholder='Email Address'
{...register("email", {required:true})}
className='bg-[#333333] px-5 py-3 rounded outline-none text-white w-full'
/>
{/* error */}
{
errors.email && (
<p className='text-[#E87C08] text-sm ' >Please enter a valid email address</p>
)
}
</label>
{/* password */}
<label>
<input
type="password"
placeholder='Password'
{...register("password", {required:true})}
className='bg-[#333333] px-5 py-3 rounded outline-none text-white w-full'
/>
{
errors.password && (
<p className='text-[#E87C08] text-sm ' >Please enter a password</p>
)
}
</label>
{/* button */}
<button
type='submit'
className='bg-[#E50914] text-white font-medium py-3 rounded mt-6 '
>
Sign Up
</button>
{/* sign in */}
<button
className='text-white'
onClick={() => navigate("/")}
>
Sign in
</button>
</form>
</div>
)
}
export default SignUpForm
|
import React from 'react'
import { mochain, overusedGrotesk } from '@/utils/Fonts'
import Experience from '@/components/Experience'
import Project from '@/components/Project'
import Tools from '@/components/Tools'
import BlogRoute from '@/components/BlogRoute'
const Home = () => {
return (
<main className="transition-all duration-75 flex flex-col w-[90dvw] md:w-[68dvw] mx-auto my-6">
<div className="space-y-3">
<h1 className={`text-5xl md:text-7xl ${mochain.variable} font-mochain`}>
Evans Elabo
</h1>
<h5
className={`text-xl md:text-2xl tracking-widest ${overusedGrotesk.variable} font-overusedGrotesk`}
>
Software Engineer
</h5>
</div>
<div className="my-6 ">
<p
className={`text-left text-base md:text-xl ${overusedGrotesk.variable} font-overusedGrotesk`}
>
Aspiring Linguistics graduate at{' '}
<span>
<a
href="https://www.knust.edu.gh/"
target="_blank"
className="underline
"
>
Kwame Nkrumah University of Science and Technology
</a>
</span>{' '}
with a strong passion for Computational Linguistics and also a
Frontend Engineer at{' '}
<span>
<a
href="https://slightlytechie.com"
target="_blank"
className="underline"
>
SlightlyTechie
</a>
</span>{' '}
with experience in building and designing user-friendly web
applications. I am always looking for opportunities to learn and grow.
<br />
<br />
Feel Free to explore my work and{' '}
<span>
<a href="mailto:ellaboevans@gmail.com" className="underline">
reach out
</a>
</span>{' '}
to me if you're interested in working with me.
</p>
<br />
<p
className={`text-left text-base md:text-xl ${overusedGrotesk.variable} font-overusedGrotesk font-semibold`}
>
Fun Fact: "Big money awaits in coding."
</p>
</div>
{/* Blog Route */}
<BlogRoute />
{/* Experience */}
<Experience title="Experiences" />
{/* Project */}
<Project title="Projects" />
{/* Languages and Tools */}
<Tools title="Languages & Tools" />
</main>
)
}
export default Home
|
import React, { Component } from 'react';
export default class ErrorBoundary extends Component {
constructor(props){
super(props)
this.state = {
hasError: false
}
}
static getDerivedStateFromError(error){
return {
hasError: true
}
}
componentDidCatch(error, errorinfo){
console.log(error)
console.log(errorinfo)
}
render() {
if(this.state.hasError){
return <h1>Something went wrong</h1>
}
return this.props.children
}
}
|
import { PrismaClient, Role } from '@prisma/client';
import { generateId } from 'lucia';
import { webcrypto } from 'node:crypto';
import { Argon2id } from 'oslo/password';
const db = new PrismaClient();
const main = async () => {
globalThis.crypto = webcrypto as Crypto;
console.log('Started Seeding');
const id = generateId(15);
await db.user.upsert({
where: {
email: 'admin@admin.com'
},
update: {},
create: {
id: id,
email: 'admin@admin.com',
emailVerified: true,
hashedPassword: await new Argon2id().hash('admin'),
role: Role.GRANT_ADMIN,
gAdminInstance: {
connectOrCreate: {
where: {
userId: id
},
create: {
organization: {
connectOrCreate: {
where: {
name: 'admin'
},
create: {
name: 'admin',
description: 'admin organization. use for tests'
}
}
}
}
}
},
profile: {
connectOrCreate: {
where: {
userId: id
},
create: {
firstName: 'Admin FName',
lastName: 'Admin LName',
dateOfBirth: new Date('2000-01-01')
}
}
}
},
include: {
gAdminInstance: true,
profile: true
}
});
console.log('Finished Seeding');
};
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await db.$disconnect();
});
|
# Implementation notes for "Curve Fitting" (curve-fitting)
## Model
The model of curve-fitting uses a series of AXON properties to update the curve. Each data point is represented in the
model as `Point`. `Point` stores its position and error. Each data point is kept in the observable array Points that
handles the coming and going of data points.
`Points` is used extensively in calculation of the regression coefficients. `Points` is responsible for filtering out
irrelevant points.
`Curve` determines the coefficients of the polynomial in an array called coefficients. The slider parameters (for '
Adjustable Fit') can be passed as coefficients or calculated based on least squares regression (for 'Best Fit'). `Curve`
calculates the r-squared and chi-squared deviations according to the weighted chi-squared regression.
For 'Adjustable Fit', the standard r-squared value can be negative. For the purposes of this simulation, in cases of a
negative r-squared, the r-squared value is shown to be zero. The classical chi-squared equation is equal to zero when
the number of points is less than the number of degrees of freedom (i.e order of polynomial + 1), since a 'Best Fit'
curve would go through all the data points in most circumstances. For the purpose of this simulation, in 'Adjustable
Fit' mode, the chi-squared value is not assumed to be zero in such situations (See Curve.js for more details).
`CurveShape` converts the polynomial of the curve into a series of small lines.
## View
`BucketNode` is responsible for handling the points coming out of the bucket.
Almost none of the nodes need to be disposed because they are instantiated a finite number of times and last for the
duration of the sim. `PointNode` is the exception as it needs a dispose, and it gets disposed in `BucketNode`.
This simulation includes query parameters in `CurveFittingQueryParameters` that are useful for debugging and should be
shared with the QA team.
|
package com.example.foodrecommenderapp.admin.report.presentation
import android.content.res.Configuration.UI_MODE_NIGHT_NO
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.foodrecommenderapp.admin.common.presentation.AdminEvents
import com.example.foodrecommenderapp.admin.common.presentation.AdminSharedViewModel
import com.example.foodrecommenderapp.admin.common.presentation.AdminState
import com.example.foodrecommenderapp.admin.report.model.Reports
import com.example.foodrecommenderapp.common.UiEvent
import com.example.foodrecommenderapp.common.presentation.components.ErrorDialog
import com.example.foodrecommenderapp.ui.theme.FoodRecommenderAppTheme
import com.maxkeppeker.sheets.core.models.base.rememberUseCaseState
import com.maxkeppeler.sheets.calendar.CalendarDialog
import com.maxkeppeler.sheets.calendar.models.CalendarConfig
import com.maxkeppeler.sheets.calendar.models.CalendarSelection
import com.maxkeppeler.sheets.calendar.models.CalendarStyle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import timber.log.Timber
import kotlin.random.Random
@Composable
fun ReportsScreen(
viewModel: AdminSharedViewModel
) {
ReportsScreenContent(
state = viewModel.state,
onEvent = viewModel::onEvent
)
}
@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class)
@Composable
fun ReportsScreenContent(
modifier: Modifier = Modifier,
state: AdminState = AdminState(),
onEvent: (AdminEvents) -> Unit,
) {
val calenderState = rememberUseCaseState()
CalendarDialog(
state = calenderState,
config = CalendarConfig(
yearSelection = true,
monthSelection = true,
style = CalendarStyle.MONTH,
),
selection = CalendarSelection.Date { newDate ->
onEvent(AdminEvents.OnSelectDate(newDate.toString()))
},
)
Box(
modifier = Modifier
.fillMaxSize()
.background(color = MaterialTheme.colorScheme.background)
) {
if (state.isLoading) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center),
color = MaterialTheme.colorScheme.primary
)
}
if (state.showErrorDialog) {
ErrorDialog(
errorMessage = state.errorMessage,
onDismissDialog = { onEvent(AdminEvents.OnDismissErrorDialog) }
)
}
if (state.showEmptyScreen) {
EmptyDataScreen()
}
Column(
modifier = modifier
.fillMaxSize()
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier.padding(horizontal = 16.dp),
text = state.date,
style = MaterialTheme.typography.bodySmall.copy(fontSize = 18.sp),
color = MaterialTheme.colorScheme.onBackground
)
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Total Searches",
style = MaterialTheme.typography.bodySmall.copy(fontSize = 18.sp),
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f),
)
Spacer(modifier = Modifier.height(6.dp))
Text(
modifier = Modifier.padding(horizontal = 16.dp),
text = state.reports?.totalSearches.toString(),
style = MaterialTheme.typography.bodySmall.copy(fontSize = 20.sp),
color = MaterialTheme.colorScheme.onBackground
)
}
IconButton(onClick = {
calenderState.show()
}) {
Icon(
imageVector = Icons.Default.CalendarMonth,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)
)
}
}
Spacer(modifier = Modifier.height(16.dp))
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(state.reports?.preferences?.keys?.toList() ?: emptyList()) { key ->
val map = state.reports?.preferences?.get(key)
Column(
modifier = Modifier.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.Center
) {
Text(
text = key.uppercase(),
style = MaterialTheme.typography.titleSmall.copy(fontSize = 20.sp),
color = MaterialTheme.colorScheme.onBackground
)
FlowRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(2.dp),
maxItemsInEachRow = 3
) {
map?.forEach {
val randomColor = Color(
red = Random.nextFloat(),
green = Random.nextFloat(),
blue = Random.nextFloat()
)
Card(
modifier = Modifier.padding(8.dp),
) {
Row(
modifier = Modifier.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.background(
color = randomColor,
shape = CircleShape
)
.size(20.dp)
)
Text(
modifier = Modifier.padding(start = 8.dp),
text = "${it.key}:",
style = MaterialTheme.typography.bodySmall.copy(
fontSize = 18.sp
),
)
Text(
modifier = Modifier.padding(start = 4.dp),
text = it.value.toString(),
style = MaterialTheme.typography.bodySmall.copy(
fontSize = 18.sp
),
)
}
}
}
}
}
}
}
}
}
}
@Composable
fun EmptyDataScreen(
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(
imageVector = Icons.Default.ErrorOutline,
contentDescription = "No data",
tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
modifier = Modifier.size(100.dp)
)
Text(
text = "No Searches for this day",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.3f),
modifier = Modifier.padding(top = 16.dp)
)
}
}
}
@Preview(showBackground = true, uiMode = UI_MODE_NIGHT_YES)
@Preview(showBackground = true, uiMode = UI_MODE_NIGHT_NO)
@Composable
private fun PreviewReports() {
FoodRecommenderAppTheme {
ReportsScreenContent(
state = AdminState(
date = "14,march 2024",
reports = Reports(
totalSearches = 100,
preferences = mapOf(
"Preference 1" to mapOf(
"Item 1" to 10,
"Item 2" to 20,
"Item 3" to 30
),
"Preference 2" to mapOf(
"Item 1" to 10,
"Item 2" to 20,
"Item 3" to 30
),
"Preference 3" to mapOf(
"Item 1" to 10,
"Item 2" to 20,
"Item 3" to 30
)
)
)
),
onEvent = {}
)
}
}
|
package com.slothdeboss.enefte.ui.screens.onboarding.presentation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.navigation.NavHostController
import com.slothdeboss.enefte.ui.navigation.OnboardingDestinations
import org.koin.androidx.compose.koinViewModel
@Composable
fun OnboardingRoute(
navController: NavHostController
) {
val viewModel: OnboardingViewModel = koinViewModel()
val step by viewModel.onboardingStep.collectAsState()
val shouldNavigateForward by viewModel.shouldNavigateForward.collectAsState()
LaunchedEffect(shouldNavigateForward) {
if (shouldNavigateForward) {
navController.navigate(OnboardingDestinations.START)
}
}
OnboardingScreen(
onboardingStep = step,
onNextClick = viewModel::onNextClick
)
}
|
import React, { Component } from "react";
import Title from "../Title";
import CartColumns from "./CartColumns";
import EmptyCart from "./EmptyCart";
import CartList from "./CartList";
import { ProductConsumer } from "../../context";
import CartTotals from "./CartTotals";
import firebase from "firebase";
export default class Cart extends Component {
state = { isSignedIn: false };
componentDidMount = () => {
firebase.auth().onAuthStateChanged(user => {
this.setState({ isSignedIn: !!user });
console.log("user", user);
});
};
render() {
return (
<>
<ProductConsumer>
{value => {
const { cart } = value;
if (cart.length > 0 || this.state.isSignedIn) {
return (
<>
<Title name="your" title="cart " />
<CartColumns />
<CartList value={value} />
<CartTotals value={value} history={this.props.history} />
</>
);
} else {
return <EmptyCart />;
}
}}
</ProductConsumer>
</>
);
}
}
|
/*
* Nextcloud Talk application
*
* @author Mario Danic
* Copyright (C) 2017-2018 Mario Danic <mario@lovelyhq.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moyn.talk.webrtc;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.bluelinelabs.logansquare.LoganSquare;
import com.moyn.talk.R;
import com.moyn.talk.application.NextcloudTalkApplication;
import com.moyn.talk.events.NetworkEvent;
import com.moyn.talk.events.WebSocketCommunicationEvent;
import com.moyn.talk.models.database.UserEntity;
import com.moyn.talk.models.json.participants.Participant;
import com.moyn.talk.models.json.signaling.NCMessageWrapper;
import com.moyn.talk.models.json.signaling.NCSignalingMessage;
import com.moyn.talk.models.json.websocket.BaseWebSocketMessage;
import com.moyn.talk.models.json.websocket.ByeWebSocketMessage;
import com.moyn.talk.models.json.websocket.CallOverallWebSocketMessage;
import com.moyn.talk.models.json.websocket.ErrorOverallWebSocketMessage;
import com.moyn.talk.models.json.websocket.EventOverallWebSocketMessage;
import com.moyn.talk.models.json.websocket.HelloResponseOverallWebSocketMessage;
import com.moyn.talk.models.json.websocket.JoinedRoomOverallWebSocketMessage;
import com.moyn.talk.utils.MagicMap;
import com.moyn.talk.utils.bundle.BundleKeys;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import autodagger.AutoInjector;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
import static com.moyn.talk.models.json.participants.Participant.ActorType.GUESTS;
import static com.moyn.talk.models.json.participants.Participant.ActorType.USERS;
@AutoInjector(NextcloudTalkApplication.class)
public class MagicWebSocketInstance extends WebSocketListener {
private static final String TAG = "MagicWebSocketInstance";
@Inject
OkHttpClient okHttpClient;
@Inject
EventBus eventBus;
@Inject
Context context;
private UserEntity conversationUser;
private String webSocketTicket;
private String resumeId;
private String sessionId;
private boolean hasMCU;
private boolean connected;
private WebSocketConnectionHelper webSocketConnectionHelper;
private WebSocket internalWebSocket;
private MagicMap magicMap;
private String connectionUrl;
private String currentRoomToken;
private int restartCount = 0;
private boolean reconnecting = false;
private HashMap<String, Participant> usersHashMap;
private List<String> messagesQueue = new ArrayList<>();
MagicWebSocketInstance(UserEntity conversationUser, String connectionUrl, String webSocketTicket) {
NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
this.connectionUrl = connectionUrl;
this.conversationUser = conversationUser;
this.webSocketTicket = webSocketTicket;
this.webSocketConnectionHelper = new WebSocketConnectionHelper();
this.usersHashMap = new HashMap<>();
magicMap = new MagicMap();
connected = false;
eventBus.register(this);
restartWebSocket();
}
private void sendHello() {
try {
if (TextUtils.isEmpty(resumeId)) {
internalWebSocket.send(LoganSquare.serialize(webSocketConnectionHelper.getAssembledHelloModel(conversationUser, webSocketTicket)));
} else {
internalWebSocket.send(LoganSquare.serialize(webSocketConnectionHelper.getAssembledHelloModelForResume(resumeId)));
}
} catch (IOException e) {
Log.e(TAG, "Failed to serialize hello model");
}
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
internalWebSocket = webSocket;
sendHello();
}
private void closeWebSocket(WebSocket webSocket) {
webSocket.close(1000, null);
webSocket.cancel();
if (webSocket == internalWebSocket) {
connected = false;
messagesQueue = new ArrayList<>();
}
restartWebSocket();
}
public void clearResumeId() {
resumeId = "";
}
public void restartWebSocket() {
reconnecting = true;
// TODO: when improving logging, keep in mind this issue: https://github.com/nextcloud/talk-android/issues/1013
Log.d(TAG, "restartWebSocket: " + connectionUrl);
Request request = new Request.Builder().url(connectionUrl).build();
okHttpClient.newWebSocket(request, this);
restartCount++;
}
@Override
public void onMessage(WebSocket webSocket, String text) {
if (webSocket == internalWebSocket) {
Log.d(TAG, "Receiving : " + webSocket.toString() + " " + text);
try {
BaseWebSocketMessage baseWebSocketMessage = LoganSquare.parse(text, BaseWebSocketMessage.class);
String messageType = baseWebSocketMessage.getType();
switch (messageType) {
case "hello":
connected = true;
reconnecting = false;
restartCount = 0;
String oldResumeId = resumeId;
HelloResponseOverallWebSocketMessage helloResponseWebSocketMessage = LoganSquare.parse(text, HelloResponseOverallWebSocketMessage.class);
resumeId = helloResponseWebSocketMessage.getHelloResponseWebSocketMessage().getResumeId();
sessionId = helloResponseWebSocketMessage.getHelloResponseWebSocketMessage().getSessionId();
hasMCU = helloResponseWebSocketMessage.getHelloResponseWebSocketMessage().serverHasMCUSupport();
for (int i = 0; i < messagesQueue.size(); i++) {
webSocket.send(messagesQueue.get(i));
}
messagesQueue = new ArrayList<>();
HashMap<String, String> helloHasHap = new HashMap<>();
if (!TextUtils.isEmpty(oldResumeId)) {
helloHasHap.put("oldResumeId", oldResumeId);
} else {
currentRoomToken = "";
}
if (!TextUtils.isEmpty(currentRoomToken)) {
helloHasHap.put("roomToken", currentRoomToken);
}
eventBus.post(new WebSocketCommunicationEvent("hello", helloHasHap));
break;
case "error":
Log.e(TAG, "Received error: " + text);
ErrorOverallWebSocketMessage errorOverallWebSocketMessage = LoganSquare.parse(text, ErrorOverallWebSocketMessage.class);
if (("no_such_session").equals(errorOverallWebSocketMessage.getErrorWebSocketMessage().getCode())) {
Log.d(TAG, "WebSocket " + webSocket.hashCode() + " resumeID " + resumeId + " expired");
resumeId = "";
currentRoomToken = "";
restartWebSocket();
} else if (("hello_expected").equals(errorOverallWebSocketMessage.getErrorWebSocketMessage().getCode())) {
restartWebSocket();
}
break;
case "room":
JoinedRoomOverallWebSocketMessage joinedRoomOverallWebSocketMessage = LoganSquare.parse(text, JoinedRoomOverallWebSocketMessage.class);
currentRoomToken = joinedRoomOverallWebSocketMessage.getRoomWebSocketMessage().getRoomId();
if (joinedRoomOverallWebSocketMessage.getRoomWebSocketMessage().getRoomPropertiesWebSocketMessage() != null && !TextUtils.isEmpty(currentRoomToken)) {
sendRoomJoinedEvent();
}
break;
case "event":
EventOverallWebSocketMessage eventOverallWebSocketMessage = LoganSquare.parse(text, EventOverallWebSocketMessage.class);
if (eventOverallWebSocketMessage.getEventMap() != null) {
String target = (String) eventOverallWebSocketMessage.getEventMap().get("target");
switch (target) {
case "room":
if (eventOverallWebSocketMessage.getEventMap().get("type").equals("message")) {
Map<String, Object> messageHashMap =
(Map<String, Object>) eventOverallWebSocketMessage.getEventMap().get("message");
if (messageHashMap.containsKey("data")) {
Map<String, Object> dataHashMap = (Map<String, Object>) messageHashMap.get(
"data");
if (dataHashMap.containsKey("chat")) {
boolean shouldRefreshChat;
Map<String, Object> chatMap = (Map<String, Object>) dataHashMap.get("chat");
if (chatMap.containsKey("refresh")) {
shouldRefreshChat = (boolean) chatMap.get("refresh");
if (shouldRefreshChat) {
HashMap<String, String> refreshChatHashMap = new HashMap<>();
refreshChatHashMap.put(BundleKeys.INSTANCE.getKEY_ROOM_TOKEN(), (String) messageHashMap.get("roomid"));
refreshChatHashMap.put(BundleKeys.INSTANCE.getKEY_INTERNAL_USER_ID(), Long.toString(conversationUser.getId()));
eventBus.post(new WebSocketCommunicationEvent("refreshChat", refreshChatHashMap));
}
}
}
}
} else if (eventOverallWebSocketMessage.getEventMap().get("type").equals("join")) {
List<HashMap<String, Object>> joinEventMap = (List<HashMap<String, Object>>) eventOverallWebSocketMessage.getEventMap().get("join");
HashMap<String, Object> internalHashMap;
Participant participant;
for (int i = 0; i < joinEventMap.size(); i++) {
internalHashMap = joinEventMap.get(i);
HashMap<String, Object> userMap = (HashMap<String, Object>) internalHashMap.get("user");
participant = new Participant();
String userId = (String) internalHashMap.get("userid");
if (userId != null) {
participant.setActorType(USERS);
participant.setActorId(userId);
} else {
participant.setActorType(GUESTS);
// FIXME seems to be not given by the HPB: participant.setActorId();
}
if (userMap != null) {
// There is no "user" attribute for guest participants.
participant.setDisplayName((String) userMap.get("displayname"));
}
usersHashMap.put((String) internalHashMap.get("sessionid"), participant);
}
}
break;
case "participants":
if (eventOverallWebSocketMessage.getEventMap().get("type").equals("update")) {
HashMap<String, String> refreshChatHashMap = new HashMap<>();
HashMap<String, Object> updateEventMap = (HashMap<String, Object>) eventOverallWebSocketMessage.getEventMap().get("update");
refreshChatHashMap.put("roomToken", (String) updateEventMap.get("roomid"));
refreshChatHashMap.put("jobId", Integer.toString(magicMap.add(updateEventMap.get("users"))));
eventBus.post(new WebSocketCommunicationEvent("participantsUpdate", refreshChatHashMap));
}
break;
}
}
break;
case "message":
CallOverallWebSocketMessage callOverallWebSocketMessage = LoganSquare.parse(text, CallOverallWebSocketMessage.class);
NCSignalingMessage ncSignalingMessage = callOverallWebSocketMessage.getCallWebSocketMessage().getNcSignalingMessage();
if (TextUtils.isEmpty(ncSignalingMessage.getFrom()) && callOverallWebSocketMessage.getCallWebSocketMessage().getSenderWebSocketMessage() != null) {
ncSignalingMessage.setFrom(callOverallWebSocketMessage.getCallWebSocketMessage().getSenderWebSocketMessage().getSessionId());
}
if (!TextUtils.isEmpty(ncSignalingMessage.getFrom())) {
HashMap<String, String> messageHashMap = new HashMap<>();
messageHashMap.put("jobId", Integer.toString(magicMap.add(ncSignalingMessage)));
eventBus.post(new WebSocketCommunicationEvent("signalingMessage", messageHashMap));
}
break;
case "bye":
connected = false;
resumeId = "";
default:
break;
}
} catch (IOException e) {
Log.e(TAG, "Failed to recognize WebSocket message", e);
}
}
}
private void sendRoomJoinedEvent() {
HashMap<String, String> joinRoomHashMap = new HashMap<>();
joinRoomHashMap.put("roomToken", currentRoomToken);
eventBus.post(new WebSocketCommunicationEvent("roomJoined", joinRoomHashMap));
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
Log.d(TAG, "Receiving bytes : " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
Log.d(TAG, "Closing : " + code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
Log.d(TAG, "Error : WebSocket " + webSocket.hashCode() + " onFailure: " + t.getMessage());
closeWebSocket(webSocket);
}
public String getSessionId() {
return sessionId;
}
public boolean hasMCU() {
return hasMCU;
}
public void joinRoomWithRoomTokenAndSession(String roomToken, String normalBackendSession) {
Log.d(TAG, "joinRoomWithRoomTokenAndSession");
Log.d(TAG, " roomToken: " + roomToken);
Log.d(TAG, " session: " + normalBackendSession);
try {
String message = LoganSquare.serialize(webSocketConnectionHelper.getAssembledJoinOrLeaveRoomModel(roomToken, normalBackendSession));
if (!connected || reconnecting) {
messagesQueue.add(message);
} else {
if (roomToken.equals(currentRoomToken)) {
sendRoomJoinedEvent();
} else {
internalWebSocket.send(message);
}
}
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
public void sendCallMessage(NCMessageWrapper ncMessageWrapper) {
try {
String message = LoganSquare.serialize(webSocketConnectionHelper.getAssembledCallMessageModel(ncMessageWrapper));
if (!connected || reconnecting) {
messagesQueue.add(message);
} else {
internalWebSocket.send(message);
}
} catch (IOException e) {
Log.e(TAG, "Failed to serialize signaling message", e);
}
}
public Object getJobWithId(Integer id) {
Object copyJob = magicMap.get(id);
magicMap.remove(id);
return copyJob;
}
public void requestOfferForSessionIdWithType(String sessionIdParam, String roomType) {
try {
String message = LoganSquare.serialize(webSocketConnectionHelper.getAssembledRequestOfferModel(sessionIdParam, roomType));
if (!connected || reconnecting) {
messagesQueue.add(message);
} else {
internalWebSocket.send(message);
}
} catch (IOException e) {
Log.e(TAG, "Failed to offer request. sessionIdParam: " + sessionIdParam + " roomType:" + roomType, e);
}
}
void sendBye() {
if (connected) {
try {
ByeWebSocketMessage byeWebSocketMessage = new ByeWebSocketMessage();
byeWebSocketMessage.setType("bye");
byeWebSocketMessage.setBye(new HashMap<>());
internalWebSocket.send(LoganSquare.serialize(byeWebSocketMessage));
} catch (IOException e) {
Log.e(TAG, "Failed to serialize bye message");
}
}
}
public boolean isConnected() {
return connected;
}
public String getDisplayNameForSession(String session) {
Participant participant = usersHashMap.get(session);
if (participant != null) {
if (participant.getDisplayName() != null) {
return participant.getDisplayName();
}
}
return NextcloudTalkApplication.Companion.getSharedApplication().getString(R.string.nc_nick_guest);
}
public String getUserIdForSession(String session) {
Participant participant = usersHashMap.get(session);
if (participant != null) {
if (participant.getActorType() == USERS) {
return participant.getActorId();
}
}
return "";
}
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(NetworkEvent networkEvent) {
if (networkEvent.getNetworkConnectionEvent().equals(NetworkEvent.NetworkConnectionEvent.NETWORK_CONNECTED) && !isConnected()) {
restartWebSocket();
}
}
}
|
import {
IconButton,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
} from "@mui/material";
import {
DownloadOutlined,
PauseCircleOutlineOutlined,
PlayCircleOutline,
StopCircleOutlined,
} from "@mui/icons-material";
import useAuth from "../hooks/useAuth";
const DockerContainersTable = ({ containerList }) => {
const { auth } = useAuth();
const { socket } = auth;
const craftMessage = (type, data) => {
return JSON.stringify({ type, data });
};
const handleDownloadLogs = (containerName) => {
socket.send(craftMessage("container-logs", containerName));
};
const handleStopContainer = (containerName) => {
socket.send(craftMessage("stop-container", containerName));
};
const handlePauseContainer = (containerName) => {
socket.send(craftMessage("pause-container", containerName));
};
const handleUnpauseContainer = (containerName) => {
socket.send(craftMessage("unpause-container", containerName));
};
return (
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>Name</TableCell>
<TableCell>Image</TableCell>
<TableCell>Ports</TableCell>
<TableCell>Status</TableCell>
<TableCell>Logs</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{containerList.map((container) => (
<TableRow key={container.containerId}>
<TableCell>{container.containerId}</TableCell>
<TableCell>{container.containerName}</TableCell>
<TableCell>{container.containerImage}</TableCell>
<TableCell>{JSON.stringify(container.containerPorts)}</TableCell>
<TableCell>{container.containerStatus}</TableCell>
<TableCell>
<IconButton
onClick={() => handleDownloadLogs(container.containerName)}
>
<DownloadOutlined />
</IconButton>
</TableCell>
<TableCell>
<IconButton
onClick={() => handleStopContainer(container.containerName)}
>
<StopCircleOutlined />
</IconButton>
{container.containerStatus === "paused" ? (
<IconButton
onClick={() =>
handleUnpauseContainer(container.containerName)
}
>
<PlayCircleOutline />
</IconButton>
) : (
<IconButton
onClick={() =>
handlePauseContainer(container.containerName)
}
>
<PauseCircleOutlineOutlined />
</IconButton>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
};
export default DockerContainersTable;
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { isEmpty, merge } from 'lodash';
import type {
AggregationsTermsAggregateBase,
AggregationsStringTermsBucketKeys,
AggregationsBuckets,
} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient, Logger } from '@kbn/core/server';
import { replaceDotSymbols } from './replace_dots_with_underscores';
import { NUM_ALERTING_RULE_TYPES } from '../alerting_usage_collector';
interface Opts {
esClient: ElasticsearchClient;
taskManagerIndex: string;
logger: Logger;
}
interface GetFailedAndUnrecognizedTasksAggregationBucket extends AggregationsStringTermsBucketKeys {
by_task_type: AggregationsTermsAggregateBase<AggregationsStringTermsBucketKeys>;
}
interface GetFailedAndUnrecognizedTasksResults {
hasErrors: boolean;
errorMessage?: string;
countFailedAndUnrecognizedTasks: number;
countFailedAndUnrecognizedTasksByStatus: Record<string, number>;
countFailedAndUnrecognizedTasksByStatusByType: Record<string, Record<string, number>>;
}
export async function getFailedAndUnrecognizedTasksPerDay({
esClient,
taskManagerIndex,
logger,
}: Opts): Promise<GetFailedAndUnrecognizedTasksResults> {
try {
const query = {
index: taskManagerIndex,
size: 0,
body: {
query: {
bool: {
must: [
{
bool: {
should: [
{
term: {
'task.status': 'unrecognized',
},
},
{
term: {
'task.status': 'failed',
},
},
],
},
},
{
wildcard: {
'task.taskType': {
value: 'alerting:*',
},
},
},
{
range: {
'task.runAt': {
gte: 'now-1d',
},
},
},
],
},
},
aggs: {
by_status: {
terms: {
field: 'task.status',
size: 10,
},
aggs: {
by_task_type: {
terms: {
field: 'task.taskType',
// Use number of alerting rule types because we're filtering by 'alerting:'
size: NUM_ALERTING_RULE_TYPES,
},
},
},
},
},
},
};
logger.debug(`query for getFailedAndUnrecognizedTasksPerDay - ${JSON.stringify(query)}`);
const results = await esClient.search(query);
logger.debug(
`results for getFailedAndUnrecognizedTasksPerDay query - ${JSON.stringify(results)}`
);
const aggregations = results.aggregations as {
by_status: AggregationsTermsAggregateBase<GetFailedAndUnrecognizedTasksAggregationBucket>;
};
const totalFailedAndUnrecognizedTasks =
typeof results.hits.total === 'number' ? results.hits.total : results.hits.total?.value;
const aggregationsByStatus: AggregationsBuckets<GetFailedAndUnrecognizedTasksAggregationBucket> =
aggregations.by_status.buckets as GetFailedAndUnrecognizedTasksAggregationBucket[];
return {
hasErrors: false,
...parseBucket(aggregationsByStatus),
countFailedAndUnrecognizedTasks: totalFailedAndUnrecognizedTasks ?? 0,
};
} catch (err) {
const errorMessage = err && err.message ? err.message : err.toString();
logger.warn(
`Error executing alerting telemetry task: getFailedAndUnrecognizedTasksPerDay - ${JSON.stringify(
err
)}`,
{
tags: ['alerting', 'telemetry-failed'],
error: { stack_trace: err.stack },
}
);
return {
hasErrors: true,
errorMessage,
countFailedAndUnrecognizedTasks: 0,
countFailedAndUnrecognizedTasksByStatus: {},
countFailedAndUnrecognizedTasksByStatusByType: {},
};
}
}
/**
* Bucket format:
* {
* "key": "idle", // task status
* "doc_count": 28, // number of tasks with this status
* "by_task_type": {
* "doc_count_error_upper_bound": 0,
* "sum_other_doc_count": 0,
* "buckets": [
* {
* "key": "alerting:.es-query", // breakdown of task type for status
* "doc_count": 1
* },
* {
* "key": "alerting:.index-threshold",
* "doc_count": 1
* }
* ]
* }
* }
*/
export function parseBucket(
buckets: GetFailedAndUnrecognizedTasksAggregationBucket[]
): Pick<
GetFailedAndUnrecognizedTasksResults,
'countFailedAndUnrecognizedTasksByStatus' | 'countFailedAndUnrecognizedTasksByStatusByType'
> {
return (buckets ?? []).reduce(
(summary, bucket) => {
const status: string = bucket.key;
const taskTypeBuckets = bucket?.by_task_type?.buckets as AggregationsStringTermsBucketKeys[];
const byTaskType = (taskTypeBuckets ?? []).reduce(
(acc: Record<string, number>, taskTypeBucket: AggregationsStringTermsBucketKeys) => {
const taskType: string = replaceDotSymbols(taskTypeBucket.key.replace('alerting:', ''));
return {
...acc,
[taskType]: taskTypeBucket.doc_count ?? 0,
};
},
{}
);
return {
...summary,
countFailedAndUnrecognizedTasksByStatus: {
...summary.countFailedAndUnrecognizedTasksByStatus,
[status]: bucket?.doc_count ?? 0,
},
countFailedAndUnrecognizedTasksByStatusByType: merge(
summary.countFailedAndUnrecognizedTasksByStatusByType,
isEmpty(byTaskType) ? {} : { [status]: byTaskType }
),
};
},
{
countFailedAndUnrecognizedTasksByStatus: {},
countFailedAndUnrecognizedTasksByStatusByType: {},
}
);
}
|
package fr.pederobien.mumble.server.event;
import java.util.StringJoiner;
import fr.pederobien.mumble.server.interfaces.IParameter;
public class MumbleParameterValueChangePostEvent extends MumbleParameterEvent {
private Object oldValue;
/**
* Creates an event thrown when the value of a parameter has changed.
*
* @param parameter The parameter whose the value has changed.
* @param oldValue The old parameter value.
*/
public MumbleParameterValueChangePostEvent(IParameter<?> parameter, Object oldValue) {
super(parameter);
this.oldValue = oldValue;
}
/**
* @return The old parameter value.
*/
public Object getOldValue() {
return oldValue;
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(", ", "{", "}");
joiner.add("channel=" + getParameter().getSoundModifier().getChannel().getName());
joiner.add("soundModifier=" + getParameter().getSoundModifier().getName());
joiner.add("parameter=" + getParameter().getName());
joiner.add("currentValue=" + getParameter().getValue());
joiner.add("oldValue=" + getOldValue());
return String.format("%s_%s", getName(), joiner);
}
}
|
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class CardExampleProjectCountWidget extends StatelessWidget {
const CardExampleProjectCountWidget({super.key});
@override
Widget build(BuildContext context) {
// return Column(
// children: [
// Text("Projects"),
// Text("20");
// ],
// return Column(children: [
// Row(
// children: [
// Expanded(
// child: Container(
// color: Colors.lightBlue,
// height: 100,
// width: double.infinity,
// child: Center(child: Text("Projects"))),
// ),
// ],
// ),
// Expanded(
// child: Text("20"),
// )
// ]);
return SizedBox(
height: 100,
//width: 800,
child: Card(
color: Colors.blue,
child: Padding(
padding: EdgeInsets.all(15),
child: Row(
children: [
// First Child
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
"Projects",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
Divider(
height: 20,
),
Text("20"),
],
),
),
VerticalDivider(
color: Colors.white,
thickness: 3,
),
// 2nd Child
Expanded(
// width: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text("Budget"),
Divider(
height: 20,
),
Text("24344.24L"),
],
),
),
VerticalDivider(),
// 3rd Child
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text("Expenditure"),
Divider(
height: 20,
),
Text("101418.0L"),
],
),
)
],
),
),
),
);
}
}
|
"use client";
import { CarCardProps } from "@/types";
import { useState } from "react";
import Image from "next/image";
import { CustomButton } from ".";
import { calucalateCarRent } from "@/utils";
import { CarDetails } from ".";
import { get } from "http";
import getCarImages from "@/services/car-image-api";
const CarCard = ({ car }: CarCardProps) => {
const [isOpen, setIsOpen] = useState(false);
const { make, model, year, city_mpg, transmission, drive } = car;
const rentalPrice = calucalateCarRent(city_mpg, year);
return (
<div className="car-card group">
<div className="car-card__content">
<h2 className="car-card__content-title">
{make} {model}
</h2>
</div>
<p className="flex mt-6 text-[32px] font-extrabold">
<span className="self-start text-[16px] font-semibold">$</span>
{rentalPrice}
<span className="self-end text-[16px] font-medium">/day</span>
</p>
<div className="relative w-full h-40 my-3">
<Image
alt="car"
src={getCarImages(car)}
fill
priority
className="object-contain"
/>
</div>
<div className="relative flex w-full mt-2">
<div className="flex group-hover:invisible w-full justify-between text-gray">
<div className="flex flex-col justify-center items-center gap-2">
<Image
alt="steering wheel"
src={"/steering-wheel.svg"}
width={20}
height={20}
/>
<p className="text-[14px]">
{transmission === "a" ? "Automatic" : "Manual"}
</p>
</div>
<div className="flex flex-col justify-center items-center gap-2">
<Image alt="tire" src={"/tire.svg"} width={20} height={20} />
<p className="text-[14px]">{drive.toUpperCase()}</p>
</div>
<div className="flex flex-col justify-center items-center gap-2">
<Image alt="gas" src={"/gas.svg"} width={20} height={20} />
<p className="text-[14px]">{city_mpg} MPG</p>
</div>
</div>
<div className="car-card__btn-container">
<CustomButton
title="View More"
containerStyles="w-full py-[16px] rounded-full bg-primary-blue"
textStyles="text-white text-[14px] leading-[17px] font-bold"
rightIcon="/right-arrow.svg"
handleClick={() => setIsOpen(true)}
/>
</div>
</div>
<CarDetails
isOpen={isOpen}
closeModal={() => setIsOpen(false)}
car={car}
/>
</div>
);
};
export default CarCard;
|
import DateFnsUtils from '@date-io/date-fns';
import {
AppBar,
Box,
createStyles,
Fade,
Grid,
Icon,
IconButton,
makeStyles,
MenuItem,
Slide,
TextField,
Theme,
Toolbar,
Typography,
useTheme,
} from '@material-ui/core';
import {
KeyboardDatePicker,
KeyboardTimePicker,
MuiPickersUtilsProvider,
} from '@material-ui/pickers';
import { MaterialUiPickersDate } from '@material-ui/pickers/typings/date';
import { observer } from 'mobx-react';
import React from 'react';
import { useHistory } from 'react-router-dom';
import enPickerLocale from 'date-fns/locale/en-US';
import hePickerLocale from 'date-fns/locale/he';
import ruPickerLocale from 'date-fns/locale/ru';
import { MenuTypesEnum, LanguagesEnum } from '../../models/Enum';
import CashStore from '../../stores/CashStore';
import TypesStore from '../../stores/TypesStore';
import useStores from '../../stores/UseStores';
import Helpers from '../../utility/Helpers';
import classes from './CashEditPanel.module.css';
import TranslatesStore from '../../stores/TranslatesStore';
import PropertiesStore from '../../stores/PropertiesStore';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
modalContainer: {
zIndex: theme.zIndex.modal,
background: theme.palette.background.paper,
},
firstBar: {
background: theme.palette.primary.light,
},
secondBar: {
background: theme.palette.primary.dark,
},
toolbarIcon: {
color: theme.palette.background.default,
},
body: {
padding: theme.spacing(2),
},
selectTypeIcon: {
marginRight: theme.spacing(2),
},
totalInput: {
marginTop: theme.spacing(1),
},
currencySelect: {
marginTop: theme.spacing(1),
},
})
);
interface IProps {
match: any;
}
const CashEditPanel = observer((props: IProps) => {
const {
cashStore,
typesStore,
translatesStore,
propertiesStore,
}: {
cashStore: CashStore;
typesStore: TypesStore;
translatesStore: TranslatesStore;
propertiesStore: PropertiesStore;
} = useStores();
const { translate } = translatesStore;
const styles = useStyles();
const css = Helpers.combineStyles(styles, classes);
const theme = useTheme();
const [cashId, setCashId] = React.useState('');
const [typeId, setTypeId] = React.useState('');
const [cashCurrency, setCashCurrency] = React.useState('');
const [pickerLocale, setPickerLocale] = React.useState(enPickerLocale);
React.useEffect(() => {
if (propertiesStore.currentLanguage?.name === LanguagesEnum.English) {
setPickerLocale(enPickerLocale);
} else if (propertiesStore.currentLanguage?.name === LanguagesEnum.Hebrew) {
setPickerLocale(hePickerLocale);
} else if (
propertiesStore.currentLanguage?.name === LanguagesEnum.Russian
) {
setPickerLocale(ruPickerLocale);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [propertiesStore.currentLanguage?.rtl]);
const history = useHistory();
React.useEffect(() => {
setCashId(props.match.params?.id);
setTypeId(props.match.params?.typeId);
if (cashStore.cashesLoaded) {
cashStore.getCashToSaveById(cashId);
if (!cashStore.cashToSave?.id) {
cashStore.updateCashToSaveByProp('typeName', typeId);
}
}
}, [
cashId,
cashStore,
props.match.params,
typesStore.typesLoaded,
cashStore.cashesLoaded,
typesStore,
typeId,
]);
const createdDate = new Date();
const deleteCash = async () => {
await cashStore.deleteCash(cashId);
history.push(`/${MenuTypesEnum.Records}`);
};
const cancelEdit = () => {
if (cashId) {
history.push(`/${MenuTypesEnum.Records}`);
} else {
history.push(`/${MenuTypesEnum.Cash}`);
}
};
const saveEdit = async () => {
if (!cashStore.cashToSave?.createdDate) {
cashStore.updateCashToSaveByProp('createdDate', createdDate);
}
if (cashStore.validateCashToSave()) {
await cashStore.saveCash(cashId);
history.push(`/${MenuTypesEnum.Records}`);
}
};
const selectTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const selectedTypeId = event.currentTarget.dataset.value!;
cashStore.updateCashToSaveByProp('typeName', selectedTypeId);
};
const getIconColor = (color?: string) => {
return typesStore.getColorInHex(theme, color);
};
const pickerDateChange = (date: MaterialUiPickersDate) => {
cashStore.updateCashToSaveByProp('createdDate', date);
};
const totalInputRef = React.useRef<HTMLInputElement>(null);
const descriptionKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.keyCode === 13) {
console.log(totalInputRef.current);
// eslint-disable-next-line no-unused-expressions
totalInputRef.current?.focus();
}
};
const changeDescriptionField = (
event: React.ChangeEvent<HTMLInputElement>
) => {
const description = event.currentTarget.value;
cashStore.updateCashToSaveByProp('description', description);
};
const changeTotalField = (event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = parseFloat(event.currentTarget.value);
const prop = event.currentTarget.dataset.propName!;
cashStore.updateCashToSaveByProp(prop, newValue);
};
const updateCashCurrency = () => {
const currency =
propertiesStore.getCurrencyByName(cashStore.cashToSave?.currency || '')
.name || '';
setCashCurrency(currency);
};
const changeCurrencyField = (event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = event.target.value;
cashStore.updateCashToSaveByProp('currency', newValue);
updateCashCurrency();
};
const totalFieldFocus = (event: React.FocusEvent<HTMLInputElement>) => {
event.currentTarget.select();
};
const submitOnEnterKeyUp = async (
event: React.KeyboardEvent<HTMLInputElement>
) => {
if (event.keyCode === 13) {
await saveEdit();
}
};
React.useEffect(() => {
updateCashCurrency();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cashStore.cashToSave, propertiesStore.defaultCurrency]);
return (
<Fade in timeout={1000}>
<Slide direction="up" in mountOnEnter unmountOnExit timeout={300}>
<div className={css.modalContainer}>
<AppBar position="static" className={css.firstBar}>
<Toolbar>
<Typography variant="h6">
{cashId ? translate.PaymentEdit : translate.PaymentNew}
</Typography>
</Toolbar>
</AppBar>
<AppBar position="static" color="primary" className={css.secondBar}>
<Toolbar>
<Box className={css.emptyBox} />
{cashId && (
<IconButton onClick={deleteCash}>
<Icon className={css.toolbarIcon}>delete_forever</Icon>
</IconButton>
)}
<IconButton onClick={cancelEdit}>
<Icon className={css.toolbarIcon}>close</Icon>
</IconButton>
<IconButton onClick={saveEdit}>
<Icon className={css.toolbarIcon}>done</Icon>
</IconButton>
</Toolbar>
</AppBar>
<div className={css.body}>
<TextField
error={!cashStore.cashToSave?.typeName}
select
fullWidth
label={translate.PaymentType}
className={css.dialogSelect}
value={cashStore.cashToSave?.typeName || ''}
onChange={selectTypeChange}
helperText={
!cashStore.cashToSave?.typeName
? translate.PaymentTypeIsRequired
: ''
}
>
{typesStore.types.map((type) => (
<MenuItem key={type.name} value={type.name}>
<div className={css.dialogSelectBox}>
<Icon
className={css.selectTypeIcon}
style={{ color: getIconColor(type.iconColor) }}
>
{type.icon}
</Icon>
<span>{type.label}</span>
</div>
</MenuItem>
))}
</TextField>
<MuiPickersUtilsProvider locale={pickerLocale} utils={DateFnsUtils}>
<Grid container justify="space-around" className={css.datesGrid}>
<KeyboardDatePicker
fullWidth
margin="normal"
label={translate.Date}
format="dd/MM/yyyy"
value={cashStore.cashToSave?.createdDate || createdDate}
onChange={pickerDateChange}
okLabel={translate.Select}
cancelLabel={translate.Cancel}
DialogProps={{
className: propertiesStore.currentLanguage?.rtl
? css.pickersRtl
: '',
}}
/>
<KeyboardTimePicker
fullWidth
margin="normal"
label={translate.Time}
value={cashStore.cashToSave?.createdDate || createdDate}
onChange={pickerDateChange}
okLabel={translate.Select}
cancelLabel={translate.Cancel}
DialogProps={{
className: propertiesStore.currentLanguage?.rtl
? css.pickersRtl
: '',
}}
/>
</Grid>
</MuiPickersUtilsProvider>
<TextField
fullWidth
className={css.descriptionInput}
label={translate.Description}
value={cashStore.cashToSave?.description || ''}
onChange={changeDescriptionField}
onKeyUp={descriptionKeyUp}
inputProps={{ 'data-prop-name': 'description' }}
/>
<div className={css.totalContainer}>
<TextField
inputRef={totalInputRef}
error={!cashStore.cashToSave?.total}
fullWidth
className={css.totalInput}
label={translate.PaymentTotal}
value={cashStore.cashToSave?.total || ''}
onChange={changeTotalField}
onFocus={totalFieldFocus}
onKeyUp={submitOnEnterKeyUp}
type="number"
inputProps={{ 'data-prop-name': 'total' }}
helperText={
!cashStore.cashToSave?.total
? translate.PaymentTotalIsRequired
: ''
}
/>
<TextField
fullWidth
select
className={css.currencySelect}
label={translate.Currency}
value={cashCurrency}
onChange={changeCurrencyField}
inputProps={{ 'data-prop-name': 'currency' }}
>
{propertiesStore.currencies.map((c) => (
<MenuItem key={c.name} value={c.name}>
{c.symbol}
</MenuItem>
))}
</TextField>
</div>
</div>
</div>
</Slide>
</Fade>
);
});
export default CashEditPanel;
|
import { ethers } from 'ethers';
import { writable } from 'svelte/store';
import type { Readable, Writable, Subscriber, Unsubscriber } from 'svelte/store';
import networks from '$lib/networks.json';
interface IContractState {
hasWallet: boolean;
correctChain: boolean;
chainId: number;
currentAccount: string;
}
interface IOptions {
forceChain?: boolean;
pollingInterval?: number;
reloadOnChainChage?: boolean;
}
interface INetwork {
chainId: number;
name?: string;
rpc?: string[];
shortName?: string;
chain?: string;
iconUrls?: string[];
nativeCurrency?: { name: string; symbol: string; decimals: number };
}
export default class Contract<TContract extends ethers.BaseContract, TState>
implements Readable<TState & IContractState>
{
protected network: INetwork;
protected provider: ethers.providers.JsonRpcProvider;
protected signer: ethers.Signer;
protected contract: TContract;
protected state: Writable<TState & IContractState>;
protected options: IOptions = {
reloadOnChainChage: true,
forceChain: true,
pollingInterval: 4000
};
public subscribe: (
run: Subscriber<TState & IContractState>,
invalidate: (value: TState & IContractState) => void
) => Unsubscriber;
constructor(
chainId: string | number,
address: string,
abi: ethers.ContractInterface,
initialState: TState,
options: IOptions = {}
) {
chainId = typeof chainId === 'string' ? parseInt(chainId, 16) : chainId;
this.network = <INetwork>networks.find((entry: any) => entry.chainId === chainId) || {
chainId: 1
};
this.options = { ...this.options, ...options };
/**
* _
* ___| |_ ___ _ __ ___
* / __| __/ _ \| '__/ _ \
* \__ \ || (_) | | | __/
* |___/\__\___/|_| \___|
*
*/
this.state = writable({
...initialState,
hasWallet: false,
correctChain: false,
chainId: null,
currentAccount: null
});
this.subscribe = this.state.subscribe; // Class "implements store" hack!
/**
* _ _
* _ __ _ __ _____ _(_) __| | ___ _ __ ___
* | '_ \| '__/ _ \ \ / / |/ _` |/ _ \ '__/ __|
* | |_) | | | (_) \ V /| | (_| | __/ | \__ \
* | .__/|_| \___/ \_/ |_|\__,_|\___|_| |___/
* |_|
*/
// JsonRpcProvider
this.provider = <ethers.providers.JsonRpcProvider>(
ethers.getDefaultProvider(this.network.rpc ? this.network.rpc[0] : null)
);
this.provider.pollingInterval = options.pollingInterval || 4000;
this.state.update((current) => ({
...current,
chainId: +chainId,
correctChain: chainId === this.network.chainId
}));
/**
* Initialize Contract
*/
this.contract = <TContract>new ethers.Contract(address, abi, this.provider);
}
}
|
package esercizi;
import java.util.Scanner;
public class CifrarioDiCesare {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input del testo e del numero di spostamenti
System.out.print("Inserisci il testo: ");
String testo = scanner.nextLine();
System.out.print("Inserisci il numero di spostamenti: ");
int spostamenti = scanner.nextInt();
// Scelta tra cifrare o decifrare
System.out.println("Vuoi cifrare (C) o decifrare (D)?");
char scelta = scanner.next().toUpperCase().charAt(0);
String risultato = "";
if (scelta == 'C') {
risultato = cifraCesare(testo, spostamenti);
} else if (scelta == 'D') {
risultato = decifraCesare(testo, spostamenti);
} else {
System.out.println("Scelta non valida.");
return;
}
System.out.println("Risultato: " + risultato);
}
public static String cifraCesare(String testo, int spostamenti) {
return trasforma(testo, spostamenti);
}
public static String decifraCesare(String testo, int spostamenti) {
return trasforma(testo, -spostamenti);
}
private static String trasforma(String testo, int spostamenti) {
StringBuilder risultato = new StringBuilder();
// Itera attraverso ogni carattere nel testo
for (int i = 0; i < testo.length(); i++) {
char carattere = testo.charAt(i);
// Controlla se il carattere è una lettera dell'alfabeto
if (Character.isLetter(carattere)) {
// Calcola la nuova posizione del carattere dopo lo spostamento
char nuovoCarattere = (char) ('A' + (Character.toUpperCase(carattere) - 'A' + spostamenti) % 26);
// Aggiungi il carattere cifrato al risultato
risultato.append(Character.isLowerCase(testo.charAt(i)) ? Character.toLowerCase(nuovoCarattere) : nuovoCarattere);
} else {
// Se non è una lettera, aggiungi il carattere senza modificarlo
risultato.append(carattere);
}
}
return risultato.toString();
}
}
|
package net.minecraft.world.entity.animal;
import java.util.Locale;
import javax.annotation.Nullable;
import net.minecraft.SystemUtils;
import net.minecraft.core.BlockPosition;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.syncher.DataWatcher;
import net.minecraft.network.syncher.DataWatcherObject;
import net.minecraft.network.syncher.DataWatcherRegistry;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.sounds.SoundEffect;
import net.minecraft.sounds.SoundEffects;
import net.minecraft.tags.BiomeTags;
import net.minecraft.tags.TagsFluid;
import net.minecraft.util.RandomSource;
import net.minecraft.world.DifficultyDamageScaler;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.entity.EnumMobSpawn;
import net.minecraft.world.entity.GroupDataEntity;
import net.minecraft.world.item.EnumColor;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.GeneratorAccess;
import net.minecraft.world.level.World;
import net.minecraft.world.level.WorldAccess;
import net.minecraft.world.level.block.Blocks;
public class EntityTropicalFish extends EntityFishSchool {
public static final String BUCKET_VARIANT_TAG = "BucketVariantTag";
private static final DataWatcherObject<Integer> DATA_ID_TYPE_VARIANT = DataWatcher.defineId(EntityTropicalFish.class, DataWatcherRegistry.INT);
public static final int BASE_SMALL = 0;
public static final int BASE_LARGE = 1;
private static final int BASES = 2;
private static final MinecraftKey[] BASE_TEXTURE_LOCATIONS = new MinecraftKey[]{new MinecraftKey("textures/entity/fish/tropical_a.png"), new MinecraftKey("textures/entity/fish/tropical_b.png")};
private static final MinecraftKey[] PATTERN_A_TEXTURE_LOCATIONS = new MinecraftKey[]{new MinecraftKey("textures/entity/fish/tropical_a_pattern_1.png"), new MinecraftKey("textures/entity/fish/tropical_a_pattern_2.png"), new MinecraftKey("textures/entity/fish/tropical_a_pattern_3.png"), new MinecraftKey("textures/entity/fish/tropical_a_pattern_4.png"), new MinecraftKey("textures/entity/fish/tropical_a_pattern_5.png"), new MinecraftKey("textures/entity/fish/tropical_a_pattern_6.png")};
private static final MinecraftKey[] PATTERN_B_TEXTURE_LOCATIONS = new MinecraftKey[]{new MinecraftKey("textures/entity/fish/tropical_b_pattern_1.png"), new MinecraftKey("textures/entity/fish/tropical_b_pattern_2.png"), new MinecraftKey("textures/entity/fish/tropical_b_pattern_3.png"), new MinecraftKey("textures/entity/fish/tropical_b_pattern_4.png"), new MinecraftKey("textures/entity/fish/tropical_b_pattern_5.png"), new MinecraftKey("textures/entity/fish/tropical_b_pattern_6.png")};
private static final int PATTERNS = 6;
private static final int COLORS = 15;
public static final int[] COMMON_VARIANTS = new int[]{calculateVariant(EntityTropicalFish.Variant.STRIPEY, EnumColor.ORANGE, EnumColor.GRAY), calculateVariant(EntityTropicalFish.Variant.FLOPPER, EnumColor.GRAY, EnumColor.GRAY), calculateVariant(EntityTropicalFish.Variant.FLOPPER, EnumColor.GRAY, EnumColor.BLUE), calculateVariant(EntityTropicalFish.Variant.CLAYFISH, EnumColor.WHITE, EnumColor.GRAY), calculateVariant(EntityTropicalFish.Variant.SUNSTREAK, EnumColor.BLUE, EnumColor.GRAY), calculateVariant(EntityTropicalFish.Variant.KOB, EnumColor.ORANGE, EnumColor.WHITE), calculateVariant(EntityTropicalFish.Variant.SPOTTY, EnumColor.PINK, EnumColor.LIGHT_BLUE), calculateVariant(EntityTropicalFish.Variant.BLOCKFISH, EnumColor.PURPLE, EnumColor.YELLOW), calculateVariant(EntityTropicalFish.Variant.CLAYFISH, EnumColor.WHITE, EnumColor.RED), calculateVariant(EntityTropicalFish.Variant.SPOTTY, EnumColor.WHITE, EnumColor.YELLOW), calculateVariant(EntityTropicalFish.Variant.GLITTER, EnumColor.WHITE, EnumColor.GRAY), calculateVariant(EntityTropicalFish.Variant.CLAYFISH, EnumColor.WHITE, EnumColor.ORANGE), calculateVariant(EntityTropicalFish.Variant.DASHER, EnumColor.CYAN, EnumColor.PINK), calculateVariant(EntityTropicalFish.Variant.BRINELY, EnumColor.LIME, EnumColor.LIGHT_BLUE), calculateVariant(EntityTropicalFish.Variant.BETTY, EnumColor.RED, EnumColor.WHITE), calculateVariant(EntityTropicalFish.Variant.SNOOPER, EnumColor.GRAY, EnumColor.RED), calculateVariant(EntityTropicalFish.Variant.BLOCKFISH, EnumColor.RED, EnumColor.WHITE), calculateVariant(EntityTropicalFish.Variant.FLOPPER, EnumColor.WHITE, EnumColor.YELLOW), calculateVariant(EntityTropicalFish.Variant.KOB, EnumColor.RED, EnumColor.WHITE), calculateVariant(EntityTropicalFish.Variant.SUNSTREAK, EnumColor.GRAY, EnumColor.WHITE), calculateVariant(EntityTropicalFish.Variant.DASHER, EnumColor.CYAN, EnumColor.YELLOW), calculateVariant(EntityTropicalFish.Variant.FLOPPER, EnumColor.YELLOW, EnumColor.YELLOW)};
private boolean isSchool = true;
private static int calculateVariant(EntityTropicalFish.Variant entitytropicalfish_variant, EnumColor enumcolor, EnumColor enumcolor1) {
return entitytropicalfish_variant.getBase() & 255 | (entitytropicalfish_variant.getIndex() & 255) << 8 | (enumcolor.getId() & 255) << 16 | (enumcolor1.getId() & 255) << 24;
}
public EntityTropicalFish(EntityTypes<? extends EntityTropicalFish> entitytypes, World world) {
super(entitytypes, world);
}
public static String getPredefinedName(int i) {
return "entity.minecraft.tropical_fish.predefined." + i;
}
public static EnumColor getBaseColor(int i) {
return EnumColor.byId(getBaseColorIdx(i));
}
public static EnumColor getPatternColor(int i) {
return EnumColor.byId(getPatternColorIdx(i));
}
public static String getFishTypeName(int i) {
int j = getBaseVariant(i);
int k = getPatternVariant(i);
String s = EntityTropicalFish.Variant.getPatternName(j, k);
return "entity.minecraft.tropical_fish.type." + s;
}
@Override
protected void defineSynchedData() {
super.defineSynchedData();
this.entityData.define(EntityTropicalFish.DATA_ID_TYPE_VARIANT, 0);
}
@Override
public void addAdditionalSaveData(NBTTagCompound nbttagcompound) {
super.addAdditionalSaveData(nbttagcompound);
nbttagcompound.putInt("Variant", this.getVariant());
}
@Override
public void readAdditionalSaveData(NBTTagCompound nbttagcompound) {
super.readAdditionalSaveData(nbttagcompound);
this.setVariant(nbttagcompound.getInt("Variant"));
}
public void setVariant(int i) {
this.entityData.set(EntityTropicalFish.DATA_ID_TYPE_VARIANT, i);
}
@Override
public boolean isMaxGroupSizeReached(int i) {
return !this.isSchool;
}
public int getVariant() {
return (Integer) this.entityData.get(EntityTropicalFish.DATA_ID_TYPE_VARIANT);
}
@Override
public void saveToBucketTag(ItemStack itemstack) {
super.saveToBucketTag(itemstack);
NBTTagCompound nbttagcompound = itemstack.getOrCreateTag();
nbttagcompound.putInt("BucketVariantTag", this.getVariant());
}
@Override
public ItemStack getBucketItemStack() {
return new ItemStack(Items.TROPICAL_FISH_BUCKET);
}
@Override
protected SoundEffect getAmbientSound() {
return SoundEffects.TROPICAL_FISH_AMBIENT;
}
@Override
protected SoundEffect getDeathSound() {
return SoundEffects.TROPICAL_FISH_DEATH;
}
@Override
protected SoundEffect getHurtSound(DamageSource damagesource) {
return SoundEffects.TROPICAL_FISH_HURT;
}
@Override
protected SoundEffect getFlopSound() {
return SoundEffects.TROPICAL_FISH_FLOP;
}
private static int getBaseColorIdx(int i) {
return (i & 16711680) >> 16;
}
public float[] getBaseColor() {
return EnumColor.byId(getBaseColorIdx(this.getVariant())).getTextureDiffuseColors();
}
private static int getPatternColorIdx(int i) {
return (i & -16777216) >> 24;
}
public float[] getPatternColor() {
return EnumColor.byId(getPatternColorIdx(this.getVariant())).getTextureDiffuseColors();
}
public static int getBaseVariant(int i) {
return Math.min(i & 255, 1);
}
public int getBaseVariant() {
return getBaseVariant(this.getVariant());
}
private static int getPatternVariant(int i) {
return Math.min((i & '\uff00') >> 8, 5);
}
public MinecraftKey getPatternTextureLocation() {
return getBaseVariant(this.getVariant()) == 0 ? EntityTropicalFish.PATTERN_A_TEXTURE_LOCATIONS[getPatternVariant(this.getVariant())] : EntityTropicalFish.PATTERN_B_TEXTURE_LOCATIONS[getPatternVariant(this.getVariant())];
}
public MinecraftKey getBaseTextureLocation() {
return EntityTropicalFish.BASE_TEXTURE_LOCATIONS[getBaseVariant(this.getVariant())];
}
@Nullable
@Override
public GroupDataEntity finalizeSpawn(WorldAccess worldaccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) {
Object object = super.finalizeSpawn(worldaccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound);
if (enummobspawn == EnumMobSpawn.BUCKET && nbttagcompound != null && nbttagcompound.contains("BucketVariantTag", 3)) {
this.setVariant(nbttagcompound.getInt("BucketVariantTag"));
return (GroupDataEntity) object;
} else {
RandomSource randomsource = worldaccess.getRandom();
int i;
int j;
int k;
int l;
if (object instanceof EntityTropicalFish.b) {
EntityTropicalFish.b entitytropicalfish_b = (EntityTropicalFish.b) object;
i = entitytropicalfish_b.base;
j = entitytropicalfish_b.pattern;
k = entitytropicalfish_b.baseColor;
l = entitytropicalfish_b.patternColor;
} else if ((double) randomsource.nextFloat() < 0.9D) {
int i1 = SystemUtils.getRandom(EntityTropicalFish.COMMON_VARIANTS, randomsource);
i = i1 & 255;
j = (i1 & '\uff00') >> 8;
k = (i1 & 16711680) >> 16;
l = (i1 & -16777216) >> 24;
object = new EntityTropicalFish.b(this, i, j, k, l);
} else {
this.isSchool = false;
i = randomsource.nextInt(2);
j = randomsource.nextInt(6);
k = randomsource.nextInt(15);
l = randomsource.nextInt(15);
}
this.setVariant(i | j << 8 | k << 16 | l << 24);
return (GroupDataEntity) object;
}
}
public static boolean checkTropicalFishSpawnRules(EntityTypes<EntityTropicalFish> entitytypes, GeneratorAccess generatoraccess, EnumMobSpawn enummobspawn, BlockPosition blockposition, RandomSource randomsource) {
return generatoraccess.getFluidState(blockposition.below()).is(TagsFluid.WATER) && generatoraccess.getBlockState(blockposition.above()).is(Blocks.WATER) && (generatoraccess.getBiome(blockposition).is(BiomeTags.ALLOWS_TROPICAL_FISH_SPAWNS_AT_ANY_HEIGHT) || EntityWaterAnimal.checkSurfaceWaterAnimalSpawnRules(entitytypes, generatoraccess, enummobspawn, blockposition, randomsource));
}
private static enum Variant {
KOB(0, 0), SUNSTREAK(0, 1), SNOOPER(0, 2), DASHER(0, 3), BRINELY(0, 4), SPOTTY(0, 5), FLOPPER(1, 0), STRIPEY(1, 1), GLITTER(1, 2), BLOCKFISH(1, 3), BETTY(1, 4), CLAYFISH(1, 5);
private final int base;
private final int index;
private static final EntityTropicalFish.Variant[] VALUES = values();
private Variant(int i, int j) {
this.base = i;
this.index = j;
}
public int getBase() {
return this.base;
}
public int getIndex() {
return this.index;
}
public static String getPatternName(int i, int j) {
return EntityTropicalFish.Variant.VALUES[j + 6 * i].getName();
}
public String getName() {
return this.name().toLowerCase(Locale.ROOT);
}
}
private static class b extends EntityFishSchool.a {
final int base;
final int pattern;
final int baseColor;
final int patternColor;
b(EntityTropicalFish entitytropicalfish, int i, int j, int k, int l) {
super(entitytropicalfish);
this.base = i;
this.pattern = j;
this.baseColor = k;
this.patternColor = l;
}
}
}
|
package todo
import (
"os"
"testing"
)
// Setup/cleanup for each test case.
// Call by doing defer setupDB()() before each test case.
func setupDB() func() {
Start("testing")
return func() {
err := os.Remove("testing.db")
if err != nil {
panic("failed to delete testing.db file")
}
}
}
// Test adding a todo list item
func TestAddTodo(t *testing.T) {
defer setupDB()()
item := TodoItem{Description: "Tickle the cat"}
AddTodo(&item)
result, err := FindTodo("Tickle the cat")
if err != nil {
t.Fatalf("Finding todo failed with error: %v", err)
}
if result.Description != "Tickle the cat" {
t.Fatalf("Got the wrong result from DB, %v", result)
}
if result.Done {
t.Fatalf("Newly added item is marked done by default")
}
}
// Test deleting a todo list item
func TestDeleteTodo(t *testing.T) {
defer setupDB()()
item := TodoItem{Description: "Tickle the cat"}
AddTodo(&item)
DeleteTodo(&item)
_, err := FindTodo("Tickle the cat")
if err == nil {
t.Fatalf("Got unexpected result after deleting todo")
}
}
// Test completing a todo list item
func TestCompleteTodo(t *testing.T) {
defer setupDB()()
item := TodoItem{Description: "Tickle the cat"}
AddTodo(&item)
item.Done = true
UpdateTodo(&item)
result, err := FindTodo("Tickle the cat")
if err != nil {
t.Fatalf("Finding failed with error: %v", err)
}
if !result.Done {
t.Fatalf("Todo not marked done after attempting to mark it done")
}
}
// Test listing all todo list items
func TestListTodos(t *testing.T) {
defer setupDB()()
item := TodoItem{Description: "Tickle the cat"}
AddTodo(&item)
item2 := TodoItem{Description: "Buy fishy treats"}
AddTodo(&item2)
items, err := ListTodos(1) // List page 1 of items
if err != nil {
t.Fatalf("Finding failed with error: %v", err)
}
if len(items) != 2 {
t.Fatalf("Did not list 2 todo items, listed %v instead", len(items))
}
if items[0].Description != "Tickle the cat" {
t.Fatalf("First item not found in list")
}
if items[1].Description != "Buy fishy treats" {
t.Fatalf("Second item not found in list")
}
}
|
{% extends "base.html"%}
{% load static %}
{% block css_imports %}
<script data-ad-client="ca-pub-5234591008009724" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<link href="{% static 'challenge/challenge.css' %}" rel="stylesheet">
{% endblock %}
{% block content %}
<div class="container page-container">
<div class="row">
<div class="header col-md-12">
<div class="header-items">
{% if not user.is_authenticated %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
You are not currently signed in. Consider signing in or making an account to avoid repeat challenges and track your progress.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
<h2 id="challenge_title">{{challenge.time_label_full}} Forecasting Challenge: {{challenge.stock_name}} : {{challenge.window_date|date:"M d, Y" }}</h2>
</div>
</div>
<div class="main-section">
<ul class="nav nav-tabs justify-content-center content-tabs" id="sections" role="tablist">
{% for section in sections %}
<li class="nav-item">
<a class="nav-link section-link" id="{{section|cut:' '}}" data-toggle="tab" href="#{{section|cut:' '}}-content" role="tab" aria-controls="{{section|cut:' '}}-content" {%if forloop.counter == 1%} aria-selected="true"{% else %}aria-selected="false" {% endif %}>{{section}}</a>
</li>
{% endfor %}
</ul>
<div class="tab-content">
{% for section in sections %}
{% if section == 'About' %}
<div class="tab-pane show active" id="{{section|cut:' '}}-content" role="tabpanel" aria-labelledby="{{section|cut:' '}}">
<p class="about-label">Stock Ticker:</p>
<p class="ticker">{{challenge.stock_ticker}}</h2>
<p class="about-label">Modern Stock Description:</p>
<p class="description">{{challenge.stock_description}}</p>
<p class="about-label">Stock Sector:</p>
<p class="description">{{challenge.stock_sector}}</p>
<p class="about-label">Stock Industry:</p>
<p class="description">{{challenge.stock_industry}}</p>
</div>
{% elif section == 'Historic Data' %}
<div class="tab-pane" id="{{section|cut:' '}}-content" role="tabpanel" aria-labelledby="{{section|cut:' '}}">
<div class="chart-section">
<canvas id="chart" width="1600" height="900"></canvas>
</div><br><br>
<div id="historic_data_table_section">
</div>
</div>
{% elif section == 'Financial Statements' %}
<div class="tab-pane" id="{{section|cut:' '}}-content" role="tabpanel" aria-labelledby="{{section|cut:' '}}">
<h2 class="financial-title">Most Recent Financial Statements For {{challenge.window_date|date:"M d, Y" }}</h2>
{% if challenge.statement_8k|length > 0 %}
<br><h2 class="document-title">8-K</h2>
<p class="document-help"><a href="https://www.sec.gov/fast-answers/answersform8khtm.html" target="_blank">What is this?</a></p>
<iframe src="../../files/{{challenge.id}}/8k.html" seamless class="document-holder"></iframe>
<br><a href="../../files/{{challenge.id}}/8k.html" class="btn btn-primary download-btn fixed-btn" download >Download This File</a>
{% endif %}
{% if challenge.statement_10k|length > 0 %}
<br><h2 class="document-title">10-K</h2>
<p class="document-help"><a href="https://www.sec.gov/fast-answers/answers-form10khtm.html" target="_blank">What is this?</a></p>
<iframe src="../../files/{{challenge.pk}}/10k.html" seamless class="document-holder"></iframe>
<br><a href="../../files/{{challenge.pk}}/10k.html" class="btn btn-primary download-btn fixed-btn" download >Download This File</a>
{% endif %}
{% if challenge.statement_10q|length > 0 %}
<br><h2 class="document-title">10-Q</h2>
<p class="document-help"><a href="https://www.sec.gov/fast-answers/answersform10qhtm.html" target="_blank">What is this?</a></p>
<iframe src="../../files/{{challenge.pk}}/10q.html" seamless class="document-holder"></iframe>
<br><a href="../../files/{{challenge.pk}}/10q.html" class="btn btn-primary download-btn fixed-btn" download >Download This File</a>
{% endif %}
{% if challenge.statement_13_g|length > 0 %}
<br><h2 class="document-title">13-G</h2>
<p class="document-help"><a href="https://www.sec.gov/fast-answers/answerssched13htm.html" target="_blank">What is this?</a></p>
<iframe src="../../files/{{challenge.pk}}/13g.html" seamless class="document-holder"></iframe>
<br><a href="../../files/{{challenge.pk}}/13g.html" class="btn btn-primary download-btn fixed-btn" download >Download This File</a>
{% endif %}
{% if challenge.statement_13f_hr|length > 0 %}
<br><h2 class="document-title">13F-HR</h2>
<p class="document-help"><a href="https://www.sec.gov/fast-answers/answers-form13fhtm.html" target="_blank">What is this?</a></p>
<iframe src="../../files/{{challenge.pk}}/13fhr.html" seamless class="document-holder"></iframe>
<br><a href="../../files/{{challenge.pk}}/13fhr.html" class="btn btn-primary download-btn fixed-btn" download >Download This File</a>
{% endif %}
{% if challenge.statement_sd|length > 0 %}
<br><h2 class="document-title">SD</h2>
<p class="document-help"><a href="https://www.sec.gov/about/forms/formsd.html" target="_blank">What is this?</a></p>
<iframe src="../../files/{{challenge.pk}}/sd.html" seamless class="document-holder"></iframe>
<br><a href="../../files/{{challenge.pk}}/sd.html" class="btn btn-primary download-btn fixed-btn" download >Download This File</a>
{% endif %}
</div>
{% elif section == 'Technicals' %}
<div class="tab-pane" id="{{section|cut:' '}}-content" role="tabpanel" aria-labelledby="{{section|cut:' '}}">
<div class="row">
<div class="col-md-6" id="col_1">
</div>
<div class="col-md-6" id="col_2">
</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12 result-section">
<div class="result-buttons">
<button class="btn decision-btn btn-success up-btn" onclick="guessSecurity(1)">Stock Will Go Up ↑</button>
<button class="btn decision-btn btn-lg btn-danger down-btn" onclick="guessSecurity(0)">Stock Will Go Down ↓</button>
</div>
<div class="additional_buttons">
{% if user.is_authenticated %}
<a id="go_back_button" href="/dashboard" class="btn btn-primary go-back-button">Go To Dashboard ←</a>
{% endif %}
<a id="skip_button" href="/challenge/{{challenge_type}}/next_challenge" class="btn btn-primary skip-button">Skip Challenge →</a>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.js" integrity="sha256-iAuxnf8Cwr0yrQkpf6oQG4PaL/oVmoer6V/RfX2KQws=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script>
function generateHistoricDataTable(results){
var table = "<table class='table table-striped historic-table'>";
var data = results.data;
table += '<tr><td colspan="10" class="header-row table-primary"><span id="table_toggle">Historic Data Table →</span></td></tr>'
for(i=0;i<data.length;i++){
if (i === 0) {
table += '<tr class="table-row first-row">';
} else {
table+= '<tr class="table-row">';
}
var row = data[i];
var cells = row.join(",").split(",");
for(j=0;j<cells.length;j++){
table+= "<td>";
table+= cells[j];
table+= "</th>";
}
if (i === 0) {
table += "</tr>";
} else {
table+= "</tr>";
}
}
table+= "</table>";
table += '<button id="download_historic_data" class="btn btn-primary download-btn">Download This Table</button>'
$("#historic_data_table_section").html(table);
};
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function sma(data, period) {
var last_n = data.slice(-1 * period);
var sum = (last_n.reduce((a, b) => parseFloat(a) + parseFloat(b), 0));
return sum / period;
}
// adapted from https://github.com/ItsNickBarry/exponential-moving-average/blob/patch-1/index.js
function avg(arr) {
var len = arr.length, i = -1;
var num = 0;
while (++i < len) num += Number(arr[i]);
return num / len;
}
function smooth(n) {
return 2 / (n + 1);
}
function ema(data, period) {
var c = smooth(period);
var num = avg(data.slice(0, period));
var acc = [num];
for (var i = period; i < data.length; i++) {
num = (c * Number(data[i])) + ((1 - c) * num);
acc.push(num);
}
return acc.slice(-1);
}
function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
function showPopup(error, success) {
var message = "There was error submitting your guess";
var result_msg = "{{challenge.stock_ticker}} changed {{challenge.result_amount_percent}} in {{challenge.time_label_full}}";
if (!error) {
if (success) {
message = "Nice Job! You guessed correctly! " + result_msg;
} else {
message = "You guessed incorrectly. " + result_msg;
}
}
$('.down-btn').prop('disabled', true);
$('.up-btn').prop('disabled', true);
$('#skip_button').html("Next Challenge →");
vex.dialog.confirm({
message: message,
callback: function (value) {
if (value) {
redirect("/challenge/{{challenge_type}}/next_challenge");
} else {}
},
buttons: [
$.extend({}, vex.dialog.buttons.YES, { text: 'Go To Next Challenge' }),
$.extend({}, vex.dialog.buttons.NO, { text: 'Stay Here' })
],
});
}
function guessSecurity(guess) {
var data_to_send = {};
data_to_send.guess = guess;
data_to_send.csrfmiddlewaretoken = "{{csrf_token}}";
$.ajax({
type: "POST",
url: "/challenge/{{request.resolver_match.kwargs.pk}}/",
data: data_to_send,
success: function(data) {
if (data.success === false) {
showPopup(true, false);
} else {
if (data.correct === true) {
showPopup(false, true);
} else {
showPopup(false, false);
}
}
},
error: function(data) {
showPopup(true, false);
}
});
}
$( document ).ready(function() {
vex.defaultOptions.className = 'vex-theme-os';
var stock_ticker = "{{ challenge.stock_ticker | safe }}";
var sections = {{sections | safe}};
sections = sections.map(el => el.replace(/\s/g, ''));
$("#" + sections[0]).addClass("active");
csv_string = `{{ challenge.historic_data | safe }}`;
var results = Papa.parse(csv_string);
generateHistoricDataTable(results);
$('.table-row').hide();
$("#table_toggle").click(function() {
var new_text = $("#table_toggle").html() === "Historic Data Table ↓" ? "→" : "↓";
$("#table_toggle").html("Historic Data Table " + new_text);
if (new_text === "→") {
$('.table-row').hide();
} else {
$('.table-row').show();
}
});
$("#download_historic_data").click(function() {
download("historic_data.csv", csv_string);
});
var date = [];
var close = [];
for (var i = 1; i < results.data.length; i++) {
if (results.data[i].length > 4) {
date.push(results.data[i][0]);
close.push(results.data[i][4]);
}
}
var ctx = document.getElementById("chart");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: date,
datasets: [
{
data: close,
label: "Price",
fill: false,
backgroundColor: "#357DED",
pointHoverBorderColor: "#EF8354",
pointHoverBackgroundColor: "#EF8354"
}
]
},
options: {
title: {
display: true,
text: stock_ticker + ' Historic Price',
fontSize: 30
},
legend: {
labels: {
fontSize: 20
}
},
scales: {
yAxes: [{
ticks: {
fontSize: 22
}
}],
xAxes: [{
ticks: {
fontSize: 19,
maxTicksLimit: 20
}
}]
}
}
});
var periods = [5, 10, 20, 50, 100];
for (var i = 0; i < periods.length; i++) {
var period = periods[i];
if (close.length + 1 > period) {
var s = sma(close, period).toFixed(2);
var e = ema(close, period)[0].toFixed(2);
var base_html = '<p class="technical-label">LABEL_HERE: <span class="technical-value">VALUE_HERE</span></p>';
var sma_html = base_html.replace("LABEL_HERE", "Simple Moving Average (" + period.toString() + ")").replace("VALUE_HERE", s.toString());
var ema_html = base_html.replace("LABEL_HERE", "Exponential Moving Average (" + period.toString() + ")").replace("VALUE_HERE", e.toString());
$("#col_1").append(sma_html);
$("#col_2").append(ema_html);
}
}
});
</script>
{% endblock %}
|
import { Button, Flex, VStack } from "@chakra-ui/react";
import Card from "../../../components/Card/Card";
import { useForm } from "react-hook-form";
import FormInput from "../../../components/Form/FormInput/FormInput";
import FormSelect from "../../../components/Form/FormSelect/FormSelect";
import useClient from "../../../hooks/useClient";
import { useNavigate, useParams } from "react-router-dom";
import InternalRoutes from "../../../utils/InternalRoutes";
import { useEffect, useState } from "react";
import notify from "../../../hooks/custom/useNotify";
import { ProductSchema } from "./Products";
import useProduct from "../../../hooks/useProduct";
function EditVehicle() {
const { id } = useParams();
const { getProduct, editProduct } = useProduct();
const { clients } = useClient();
const [product, setProduct] = useState<ProductSchema>({} as ProductSchema)
const navigateTo = useNavigate();
const { register, handleSubmit } = useForm({
defaultValues: {
name: "",
price: 0,
quantity: 0,
}, values: {
name: product.name,
price: product.price,
quantity: product.quantity,
}
});
useEffect(() => {
if (!id) return navigateTo(InternalRoutes.VEHICLES);
const product = getProduct(id);
if (!product) return navigateTo(InternalRoutes.VEHICLES);
setProduct(product)
}, [navigateTo, id, getProduct]);
const onCancel = () => navigateTo(InternalRoutes.VEHICLES);
const onSubmit = ({
name,
price,
quantity,
}: {
name: string;
price: number;
quantity: number;
}) => {
editProduct({name, price, quantity});
notify({message: "Veiculo editado com sucesso"})
navigateTo(InternalRoutes.VEHICLES)
};
return (
<Card>
<VStack w={"100%"}>
<VStack w="100%" gap={"8"} mb={"12"}>
<VStack align={"flex-start"} w="100%">
<FormInput name="plate" label="Placa" register={register} />
</VStack>
<VStack align={"flex-start"} w="100%">
<FormInput name="model" label="Modelo" register={register} />
</VStack>
<VStack align={"flex-start"} w="100%">
<FormInput name="color" label="Cor" register={register} />
</VStack>
<VStack align={"flex-start"} w="100%">
<FormSelect name="owner" label="Dono" register={register}>
{clients.map((client, index) => (
<option key={index} value={client.id}>
{client.nome}
</option>
))}
</FormSelect>
</VStack>
</VStack>
<Flex gap={"8"}>
<Button colorScheme="blackAlpha" onClick={onCancel}>
Voltar
</Button>
<Button colorScheme="yellow" onClick={handleSubmit(onSubmit)}>
Atualizar veiculo
</Button>
</Flex>
</VStack>
</Card>
);
}
export default EditVehicle;
|
import { KeystoneContext } from '@keystone-6/core/types'
async function addToCart(
root: any,
{ productId }: { productId: string },
context: KeystoneContext,
) {
const { session, query } = context
if (!session.itemId) {
throw new Error('You must be logged in.')
}
const allCartItems = await query.CartItem.findMany({
where: {
user: { id: { equals: session.itemId } },
product: { id: { equals: productId } },
},
query: 'id quantity',
})
const [existingCartItem] = allCartItems
if (existingCartItem) {
return await query.CartItem.updateOne({
where: { id: existingCartItem.id },
data: { quantity: existingCartItem.quantity + 1 },
})
}
return await query.CartItem.createOne({
data: {
product: { connect: { id: productId } },
user: { connect: { id: session.itemId } },
},
})
}
export default addToCart
|
/*******************************************************************************
* Copyright (c) 2006, 2008 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Martin Oberhuber (Wind River) - initial API and implementation
* Xuan Chen (IBM) - [160775] Derive from org.eclipse.rse.services.Mutex
* Xuan Chen (IBM) - [209825] add some info of printing the lock status
*******************************************************************************/
package org.eclipse.rse.services.clientserver;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* A reentrant Exclusion Lock for Threads that need to access a resource in a
* serialized manner. If the request for the lock is running on the same thread
* who is currently holding the lock, it will "borrow" the lock, and the call to
* waitForLock() will go through. A SystemOperationMonitor is accepted in order
* to support cancellation when waiting for the Mutex. This is a clone of
* {@link org.eclipse.rse.services.Mutex} with some modification to make sure the
* sequential calls to waitForLock() method in the same thread will not be
* blocked.
*
* Usage Example: <code>
* private SystemReentrantMutex fooMutex = new SystemReentrantMutex();
* boolean doFooSerialized()(ISystemOperationMonitor monitor) {
* int mutexLockStatus = SystemReentrantMutex.LOCK_STATUS_NOLOCK;
* mutexLockStatus = fooMutex.waitForLock(monitor, 1000);
* if (mutexLockStatus != SystemReentrantMutex.LOCK_STATUS_NOLOCK) {
* try {
* return doFoo();
* } finally {
* //We only release the mutex if we acquire it, not borrowed it.
* if (mutexLockStatus == SystemReentrantMutex.LOCK_STATUS_AQUIRED)
* {
* fooMutex.release();
* }
* }
* }
* return false;
* }
* </code>
*
* @since 3.0
*/
public class SystemReentrantMutex {
private boolean fLocked = false;
private List fWaitQueue = new LinkedList();
private Thread threadLockThisMutex = null;
public static final int LOCK_STATUS_NOLOCK = 0; //No lock acquired or borrowed
public static final int LOCK_STATUS_AQUIRED = 1; //Lock is acquired
public static final int LOCK_STATUS_BORROWED = 2; //Lock is borrowed, since it is running
//on the same thread as the one holding the lock
/**
* Creates an instance of <tt>SystemMutex</tt>.
*/
public SystemReentrantMutex() {
}
/**
* Try to acquire the lock maintained by this mutex.
*
* If the thread needs to wait before it can acquire the mutex, it
* will wait in a first-come-first-serve fashion. In case a progress
* monitor was given, it will be updated and checked for cancel every
* second.
*
* @param monitor SystemOperationMonitor. May be <code>null</code>.
* @param timeout Maximum wait time given in milliseconds.
* @return <code>LOCK_STATUS_AQUIRED</code> if the lock was acquired successfully.
* <code>LOCK_STATUS_BORROWED</code> if the lock was borrowed.
* <code>LOCK_STATUS_NOLOCK</code> if otherwise.
*/
public int waitForLock(ISystemOperationMonitor monitor, long timeout) {
if (Thread.interrupted()) {
return LOCK_STATUS_NOLOCK;
}
if (monitor!=null && monitor.isCancelled()) {
return LOCK_STATUS_NOLOCK;
}
final Thread myself = Thread.currentThread();
synchronized(fWaitQueue) {
if (!fLocked) {
//acquire the lock immediately.
fLocked = true;
threadLockThisMutex = myself;
return LOCK_STATUS_AQUIRED;
} else {
fWaitQueue.add(myself);
}
}
//need to wait for the lock.
int lockStatus = LOCK_STATUS_NOLOCK;
try {
long start = System.currentTimeMillis();
long timeLeft = timeout;
//It could be possible this function is called with null as monitor
//And we don't want to wait forever here
long pollTime = (timeLeft > 1000) ? 1000 : timeLeft;
long nextProgressUpdate = start+500;
boolean cancelled = false;
while (timeLeft > 0 && !cancelled && lockStatus == LOCK_STATUS_NOLOCK) {
//is it my turn yet? Check wait queue and wait
synchronized(fWaitQueue) {
if (!fLocked && fWaitQueue.get(0) == myself) {
fWaitQueue.remove(0);
fLocked = true;
lockStatus = LOCK_STATUS_AQUIRED;
threadLockThisMutex = myself;
} else
{
if (threadLockThisMutex == myself && fWaitQueue.contains(myself))
{
fWaitQueue.remove(myself);
fLocked = true;
lockStatus = LOCK_STATUS_BORROWED;
}
else
{
long waitTime = timeLeft > pollTime ? pollTime : timeLeft;
fWaitQueue.wait(waitTime);
Object firstInQueue = fWaitQueue.get(0);
boolean amIFirstInQueue = false;
if (firstInQueue == null || firstInQueue == myself)
{
amIFirstInQueue = true;
}
if (!fLocked && amIFirstInQueue) {
fWaitQueue.remove(0);
fLocked = true;
lockStatus = LOCK_STATUS_AQUIRED;
threadLockThisMutex = myself;
}
}
}
}
if (lockStatus == LOCK_STATUS_NOLOCK) {
//Need to continue waiting
long curTime = System.currentTimeMillis();
timeLeft = start + timeout - curTime;
if (monitor!=null) {
cancelled = monitor.isCancelled();
if (!cancelled && (curTime > nextProgressUpdate)) {
nextProgressUpdate+=1000;
}
}
}
}
} catch(InterruptedException e) {
//cancelled waiting -> no lock acquired
} finally {
if (lockStatus == LOCK_STATUS_NOLOCK) {
synchronized(fWaitQueue) {
fWaitQueue.remove(myself);
}
}
}
return lockStatus;
}
/**
* Release this mutex's lock.
*
* May only be called by the same thread that originally acquired
* the SystemMutex.
*/
public void release() {
synchronized(fWaitQueue) {
fLocked=false;
if (!fWaitQueue.isEmpty()) {
fWaitQueue.notifyAll();
}
}
}
/**
* Return this Mutex's lock status.
* @return <code>true</code> if this mutex is currently acquired by a thread.
*/
public boolean isLocked() {
synchronized(fWaitQueue) {
return fLocked;
}
}
/**
* Interrupt all threads waiting for the Lock, causing their
* {@link #waitForLock(ISystemOperationMonitor, long)} method to return
* <code>false</code>.
* This should be called if the resource that the Threads are
* contending for, becomes unavailable for some other reason.
*/
public void interruptAll() {
synchronized(fWaitQueue) {
Iterator it = fWaitQueue.iterator();
while (it.hasNext()) {
Thread aThread = (Thread)it.next();
aThread.interrupt();
}
}
}
/*
* Method used to debug this mutex
* uncomment it when needed
*
private void printLockMessage(int status, Thread myself)
{
if (status == LOCK_STATUS_AQUIRED)
{
System.out.println("Lock is AQUIRED by thread " + myself.getId());
}
else if (status == LOCK_STATUS_BORROWED)
{
System.out.println("Lock is BORROWED by thread " + myself.getId());
}
}
*/
}
|
# Some refactoring
rm(list = ls())
library('R2jags')
## How many iterations?
nIterations <- 10000
## Collect all priors
priors <- list(mean_alpha = 0.0,
sd_alpha = 1/sqrt(.1),
mean_beta = 0.0,
sd_beta = 1/sqrt(.1),
shape_tau = 2.0,
rate_tau = 0.5)
## Collect information about the experiment
design <- list(n_sessions = 10)
# Get parameters from prior
get_parameters_from_prior <- function(priors) {
alpha0 <- truncnorm::rtruncnorm(n = 1,
a = -2.0,
b = 2.0,
mean = priors$mean_alpha,
sd = priors$sd_alpha)
beta0 <- truncnorm::rtruncnorm(n = 1,
a = -2.0,
b = 2.0,
mean = priors$mean_beta,
sd = priors$sd_beta )
tau0 <- rgamma(n = 1,
shape = priors$shape_tau,
rate = priors$rate_tau)
parameters <- list(alpha0 = alpha0,
beta0 = beta0 ,
tau0 = tau0 )
return(parameters)
}
# Get data from parameters
get_data_from_parameters <- function(parameters, design) {
# Sample data 'Br, Bl' from the likelihood given prior sample 'th0'
Wr <- rpois(n = design$n_sessions, lambda = 50)
Wl <- rpois(n = design$n_sessions, lambda = 80)
rMean <- parameters$alpha0 / 2 + parameters$beta0 * log(Wr) / 2
lMean <- -parameters$alpha0 / 2 - parameters$beta0 * log(Wl) / 2
stdev <- 1 / sqrt(parameters$tau0)
lambda_Br0 <- rlnorm(n = design$n_sessions, meanlog = rMean, sdlog = stdev)
lambda_Bl0 <- rlnorm(n = design$n_sessions, meanlog = lMean, sdlog = stdev)
Br <- rpois(n = design$n_sessions, lambda = lambda_Br0)
Bl <- rpois(n = design$n_sessions, lambda = lambda_Bl0)
data <- list(Wr = Wr, Wl = Wl, Br = Br, Bl = Bl)
return(data)
}
# Get MCMC from data
get_mcmc_from_data <- function(data, priors, design) {
# Compute a (to-be-tested) posterior sample [th1,th2,...,thL]
# given the sample from the likelihood
observed <- list(
Br = data$Br,
Bl = data$Bl,
Wr = data$Wr,
Wl = data$Wl,
mean_alpha_prior = priors$mean_alpha,
sd_alpha_prior = priors$sd_alpha,
mean_beta_prior = priors$mean_beta,
sd_beta_prior = priors$sd_beta,
shape_tau_prior = priors$shape_tau,
rate_tau_prior = priors$rate_tau,
n_obs = design$n_sessions
)
unobserved <- c('alpha', 'beta', 'tau', 'lambda_Br', 'lambda_Bl')
write(
'model{
alpha ~ dnorm(mean_alpha_prior, pow(sd_alpha_prior, -2))T(-2,2)
beta ~ dnorm(mean_beta_prior , pow(sd_beta_prior , -2))T(-2,2)
tau ~ dgamma(shape_tau_prior, rate_tau_prior)T(0.01,)
for(i in 1:n_obs){
lambda_Br[i] ~ dlnorm( alpha/2 + beta * log(Wr[i])/2, tau)
lambda_Bl[i] ~ dlnorm(-alpha/2 - beta * log(Wl[i])/2, tau)
Br[i] ~ dpois(lambda_Br[i])
Bl[i] ~ dpois(lambda_Bl[i])
}
}',
'generative_matching.bug'
)
bayes <- jags(
data = observed,
parameters.to.save = unobserved,
model.file = 'generative_matching.bug'
)
return(bayes)
}
# Get quantiles from MCMC
get_quantiles_from_mcmc <- function(mcmc, parameters) {
alpha <- mcmc$BUGSoutput$sims.list$alpha
beta <- mcmc$BUGSoutput$sims.list$beta
tau <- mcmc$BUGSoutput$sims.list$tau
q0_alpha <- mean(parameters$alpha0 > alpha)
q0_beta <- mean(parameters$beta0 > beta )
q0_tau <- mean(parameters$tau0 > tau )
quantiles <- list(
q0_alpha = q0_alpha,
q0_beta = q0_beta,
q0_tau = q0_tau
)
return(quantiles)
}
# Compute quantiles
quantiles_alpha <- NA
quantiles_beta <- NA
quantiles_tau <- NA
for (i in 1:nIterations) {
parameters <- get_parameters_from_prior(priors = priors)
data <- get_data_from_parameters (parameters = parameters, design = design)
mcmc <- get_mcmc_from_data (data = data, priors = priors, design = design)
quantiles <- get_quantiles_from_mcmc (mcmc = mcmc, parameters = parameters)
quantiles_alpha[i] <- quantiles$q0_alpha
quantiles_beta[i] <- quantiles$q0_beta
quantiles_tau[i] <- quantiles$q0_tau
print(i)
}
# Save cache
timestamp <- format(Sys.time() , "%Y%m%d_%H%M%S")
save(file = paste0('test_matching_', timestamp, '.RData'), 'quantiles_alpha', 'quantiles_beta', 'quantiles_tau')
# Plot histograms
pdf(file = paste0('test_matching_', timestamp, '.pdf'), width = 6, height = 4)
layout(1:3)
hist(quantiles_alpha, breaks = 50)
hist(quantiles_beta , breaks = 50)
hist(quantiles_tau , breaks = 50)
dev.off()
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
function Animal(type, name, sound) {
console.log(this.type);
console.log(type);
this.type = type;
this.name = name;
this.sound = sound;
this.say = function () {
console.log(this.sound);
};
}
//프로토타입 공간에 say를 정의한다 (해당객체에 아무것도 선언되어있지않으면 프로토타입에 있는 공유값을 쓴다)
Animal.prototype.say = function () {
console.log(this.sound);
};
Animal.prototype.sharedValue = 1;
const dog = new Animal("개", "멍멍이", "멍멍");
const cat = new Animal("고양이", "야옹", "야옹");
dog.say();
cat.say();
console.log(dog.sharedValue);
console.log(cat.sharedValue);
//프로토타입에도 값이 있지만 새로 정의해주면 해당값이 출력된다.
cat.sharedValue = 2;
console.log(dog.sharedValue);
console.log(cat.sharedValue);
Animal.prototype.say.call(cat);
console.log(cat.say.call);
</script>
</body>
</html>
|
package 코딩인터뷰완전분석.Ch_08._Recursion_and_Dynamic_Programming.Q8_04_Power_Set;
import java.util.ArrayList;
public class QuestionA {
public static ArrayList<ArrayList<Integer>> getSubsets(ArrayList<Integer> set, int index) {
ArrayList<ArrayList<Integer>> allsubsets;
if (set.size() == index) { // Base case - add empty set
allsubsets = new ArrayList<ArrayList<Integer>>();
allsubsets.add(new ArrayList<Integer>());
} else {
allsubsets = getSubsets(set, index + 1);
int item = set.get(index);
ArrayList<ArrayList<Integer>> moresubsets = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> subset : allsubsets) {
ArrayList<Integer> newsubset = new ArrayList<Integer>();
newsubset.addAll(subset);
newsubset.add(item);
moresubsets.add(newsubset);
}
allsubsets.addAll(moresubsets);
}
return allsubsets;
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 3; i++) {
list.add(i);
}
ArrayList<ArrayList<Integer>> subsets = getSubsets(list, 0);
System.out.println(subsets);
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import HamburguerAdmin from './HamburguerAdmin';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
export default function ButtonAppBar({ content }) {
const classes = useStyles();
return (
<div className={ classes.root } data-testid="top-title">
<AppBar position="relative">
<Toolbar>
<Typography variant="h4" className={ classes.title }>
{content}
</Typography>
<HamburguerAdmin />
</Toolbar>
</AppBar>
</div>
);
}
ButtonAppBar.propTypes = {
content: PropTypes.string.isRequired,
};
|
//
// connection_info_.h
// IJKMediaFramework
//
// Created by 帅龙成 on 2019/6/27.
// Copyright © 2019 kuaishou. All rights reserved.
//
#pragma once
#include <memory>
#include "download/input_stream.h"
#include "data_spec.h"
#include "../include/cache_defs.h"
#include "ac_log.h"
namespace kuaishou {
namespace cache {
/**
* 所有下载一些连接/下载进度等数据
*/
struct ConnectionInfoV2 {
uint32_t id_ = -1;
// content length of the downloadable contents, may be kLengthUnset.
int64_t content_length = kLengthUnset;
// response code of the request.
int response_code = 0;
// 0 if no error, positive value for error we set, negative value for error from other library(libcurl).
int error_code = 0;
// used time of make connection.
int connection_used_time_ms = 0;
// dns resolve time
int http_dns_analyze_ms = 0;
// http read first data time
int http_first_data_ms = 0;
// the number of redirects
int redirect_count = 0;
// the last used URL
std::string effective_url = "";
// uri.
std::string uri = "";
// host.
std::string http_dns_host = "";
// ip address.
std::string ip = "";
// kwaisign
std::string sign = "";
// kwai k_ks_cache
std::string x_ks_cache = "";
std::string session_uuid = "";
std::string download_uuid = "";
bool is_range_request = false;
int64_t range_request_start = -1;
int64_t range_request_end = -1;
int64_t range_response_start = -1;
int64_t range_response_end = -1;
// file total length of the downloading file. for byte-range.
int64_t range_response_file_length = kLengthUnset;
DownloadStopReason stop_reason = kDownloadStopReasonUnknown;
// transfer_consume_ms_ 这个字段很重要,会影响cdn resource上报统计逻辑,所以重构的时候需谨慎,一定要测试100%正确
int32_t transfer_consume_ms = 0;
int64_t downloaded_bytes_from_curl = 0;
bool is_gzip = false;
/**
*
* @return 平均下载速度,单位kbps
*/
int64_t GetAvgDownloadSpeedkbps() {
return transfer_consume_ms > 0 ? downloaded_bytes_from_curl * 8 / transfer_consume_ms : 0;
}
bool IsResponseCodeSuccess() const {
return (response_code >= 200 && response_code <= 299);
}
bool IsDownloadComplete() const {
return content_length > 0 && (downloaded_bytes_from_curl >= content_length);
}
/**
* 如果是range请求,则返回range里的file_length,否则返回Content-length
*/
int64_t GetFileLength() const {
return is_range_request ? range_response_file_length : content_length;
}
};
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Universal charset detector code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* BYVoid <byvoid.kcp@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ___UCHARDET_H___
#define ___UCHARDET_H___
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
typedef void * uchardet_t;
/**
* Create an encoding detector.
* @return a handle of a instance of uchardet
*/
uchardet_t uchardet_new();
/**
* Delete an encoding detector.
* @param ud [in] handle of a instance of uchardet
*/
void uchardet_delete(uchardet_t ud);
/**
* Feed data to an encoding detector.
* @param ud [in] handle of a instance of uchardet
* @param data [in] data
* @param len [in] number of byte of data
* @return non-zero number on failure.
*/
int uchardet_handle_data(uchardet_t ud, const char * data, size_t len);
/**
* Notify an end of data to an encoding detctor.
* @param ud [in] handle of a instance of uchardet
*/
void uchardet_data_end(uchardet_t ud);
/**
* Reset an encoding detector.
* @param ud [in] handle of a instance of uchardet
*/
void uchardet_reset(uchardet_t ud);
/**
* Get the name of encoding that was detected.
* @param ud [in] handle of a instance of uchardet
* @return name of charset on success and "" on failure or pure ascii.
*/
const char * uchardet_get_charset(uchardet_t ud);
#ifdef __cplusplus
}
#endif
#endif
|
#+author: Juan E. Gómez-Morantes, PhD
#+title: Hoja de estilo no oficial para documentos simples de la Pontificia Universidad Javeriana usando LaTex
#+property: header-args :tangle ./docsimplepuj.sty
* Introducción
La presente hoja de estilo de LaTex tiene como objetivo tener una formato estandarizado para la generación de documentos simples (e.g. enunciados, programas de cursos, entregas por parte de estudiantes, reportes de avance, etc.) para la Pontificia Universidad Javeriana en Bogotá, Colombia.
Este archivo usa el paquete =org= de Emacs para tener un código fuente en formato de programación literaria para documentar el código de la hoja de estilo.
* Paquetes a utilizar
#+begin_src tex
\usepackage[margin=3cm]{geometry} %to define the margins
\usepackage[export]{adjustbox} %the export option makes it load graphicx
\usepackage{pgf} % Allows the manipulation of numeric values
\usepackage{etoolbox} % Provides functionality for the evaluation of conditional statements
\usepackage[scaled]{helvet} % Provides Helvita as sans serif font
\usepackage{ebgaramond} % Provides EB Garamond as serif font
\usepackage[T1]{fontenc} % Improves font encoding
\usepackage{xcolor} % Allows the definition of colours
\usepackage{sectsty} % Allows the formating of headings
\usepackage{colortbl} % Allows to define colour of table lines
\usepackage{titlesec} % Allows for the formating of headings
#+end_src
* Definición de colores a usar en el documento
Se define el azul institucional (tomado de [[https://www.javeriana.edu.co/recursosdb/813229/983106/Manual+de+Identidad+Visual+2018.pdf/bb8d2ae7-2b76-b755-f179-c0ea8337b567?t=1606514066712][manual de identidad visual]]) para títulos y encabezados de secciones.
#+begin_src tex
\definecolor{azulPUJ}{RGB}{44, 86, 151}
#+end_src
* Formateo de texto, títulos, y encabezados.
Se usa GaramondEB para título y texto principal, y Helvetica para encabezado de secciones.
En adición, se usan los siguientes tamaños para los encabezados de secciones:
| Sección | \Large |
| Subsección | \large |
| Subsubsección | \normalsize |
Finalmente, se define un espacio de 0.75em después de cada párrafo.
#+begin_src tex
\sectionfont{\Large\sffamily\color{azulPUJ}}
\subsectionfont{\large\sffamily\color{azulPUJ}}
\subsubsectionfont{\normalsize\sffamily\color{azulPUJ}}
\setlength{\parskip}{0.75em}
#+end_src
Se usa titlesec para reducir el espacio después de encabezados, pero conservando un espacio antes.
#+begin_src tex
\titlespacing\section{0pt}{1.2em}{0pt}
\titlespacing\subsection{0pt}{.8em}{0pt}
\titlespacing\subsubsection{0pt}{.5em}{0pt}
#+end_src
* Creación del título del documento
El documento cuenta con 3 niveles de título: título, subtítulo, y subsubtítulo. Un ejemplo de uso sería:
| Title | Asignatura X | Obligatorio |
| Subtitle | Laboratorio Y | Opcional |
| SubSubtitle | Temática del laboratorio Y | Opcional |
Para lograr un título que se adapte al uso opcional del subtítulo y el título, manteniendo un tamaño proporcional del logo de la universidad a la izquierda del título, se empieza con una altura de 4\baselineskip para la imagen y luego se aumenta si se definen sub o subsub título.
#+begin_src tex
\newtoggle{withSubtitle}
\togglefalse{withSubtitle}
\newtoggle{withSubsubtitle}
\togglefalse{withSubsubtitle}
\pgfmathsetmacro{\altura}{5}
\newcommand{\aumentarAltura}[1]{
\pgfmathsetmacro{\altura}{\altura+#1}
}
\def\@subtitle{}
\newcommand{\subtitle}[1]{
\def\@subtitle{#1}
\aumentarAltura{1}
\toggletrue{withSubtitle}
}
\def\@subsubtitle{}
\newcommand{\subsubtitle}[1]{
\def\@subsubtitle{#1}
\aumentarAltura{1}
\toggletrue{withSubsubtitle}
}
\renewcommand{\maketitle}{\bgroup\setlength{\parindent}{0pt}
\includegraphics[height=\altura\baselineskip,valign=m]{./img/logoBasico.jpg}
{
\setlength\arrayrulewidth{2pt}
\arrayrulecolor{azulPUJ}
\begin{tabular}{p{1pt}|p{1pt}l}
&& \parbox{.7\linewidth}{\Huge\color{azulPUJ}\textbf{\@title}\vspace{2pt}}\\ \iftoggle{withSubtitle}{&&\parbox{.7\linewidth}{\LARGE\color{azulPUJ}\textbf{\@subtitle}\vspace{2pt}}\\}{} \iftoggle{withSubsubtitle}{&&\parbox{.7\linewidth}{\Large\color{azulPUJ}\@subsubtitle}\\}{}
&& \\
&& \\
&& \parbox{.7\linewidth}{\color{azulPUJ}\large\@prefixAuthor\@author\vspace{2pt}} \\
&&\color{azulPUJ}\@prefixDate\@date \\
\end{tabular}
}
\vspace{3\baselineskip}
}
#+end_src
** Configuración del prefijo del autor y la fecha del documento
Se definen los siguiente comando para configurar los prefijos del autor y la fecha del documento.
#+begin_src tex
\def\@prefixAuthor{Preparado por: }
\newcommand{\prefixAuthor}[1]{
\def\@prefixAuthor{#1}
}
\def\@prefixDate{Última actualización: }
\newcommand{\prefixDate}[1]{
\def\@prefixDate{#1}
}
#+end_src
|
#pragma once
#include "chars.h"
#include "iterator.h"
#include "string_view.h"
#include <algorithm>
#include <memory>
namespace std {
class locale;
}
namespace uxs {
// --------------------------
template<typename InputIt, typename InputFn = nofunc>
unsigned from_hex(InputIt in, unsigned n_digs, InputFn fn = InputFn{}, unsigned* n_valid = nullptr) {
unsigned val = 0;
if (n_valid) { *n_valid = n_digs; }
while (n_digs) {
unsigned dig = dig_v(fn(*in));
if (dig < 16) {
val = (val << 4) | dig;
} else {
if (n_valid) { *n_valid -= n_digs; }
return val;
}
++in, --n_digs;
}
return val;
}
template<typename OutputIt, typename OutputFn = nofunc>
void to_hex(unsigned val, OutputIt out, unsigned n_digs, bool upper = false, OutputFn fn = OutputFn{}) {
const char* digs = upper ? "0123456789ABCDEF" : "0123456789abcdef";
unsigned shift = n_digs << 2;
while (shift) {
shift -= 4;
*out++ = fn(digs[(val >> shift) & 0xf]);
}
}
// --------------------------
enum class fmt_flags : unsigned {
kDefault = 0,
kDec = kDefault,
kBin = 1,
kOct = 2,
kHex = 3,
kBaseField = 3,
kFixed = 4,
kScientific = 8,
kGeneral = 0xc,
kFloatField = 0xc,
kLeft = 0x10,
kRight = 0x20,
kInternal = 0x30,
kAdjustField = 0x30,
kLeadingZeroes = 0x40,
kUpperCase = 0x80,
kAlternate = 0x100,
kSignNeg = kDefault,
kSignPos = 0x200,
kSignAlign = 0x400,
kSignField = 0x600,
};
UXS_IMPLEMENT_BITWISE_OPS_FOR_ENUM(fmt_flags, unsigned);
struct fmt_opts {
CONSTEXPR fmt_opts() = default;
CONSTEXPR fmt_opts(fmt_flags fl) : flags(fl) {}
CONSTEXPR fmt_opts(fmt_flags fl, int p) : flags(fl), prec(p) {}
CONSTEXPR fmt_opts(fmt_flags fl, int p, const std::locale* l) : flags(fl), prec(p), loc(l) {}
CONSTEXPR fmt_opts(fmt_flags fl, int p, const std::locale* l, unsigned w, int ch)
: flags(fl), prec(p), loc(l), width(w), fill(ch) {}
fmt_flags flags = fmt_flags::kDec;
int prec = -1;
const std::locale* loc = nullptr;
unsigned width = 0;
int fill = ' ';
};
// --------------------------
template<typename Ty>
class basic_membuffer {
private:
static_assert(std::is_trivially_copyable<Ty>::value && std::is_trivially_destructible<Ty>::value,
"uxs::basic_membuffer<> must have trivially copyable and destructible value type");
public:
using value_type = Ty;
explicit basic_membuffer(Ty* first, Ty* last = reinterpret_cast<Ty*>(std::numeric_limits<uintptr_t>::max())) NOEXCEPT
: curr_(first),
last_(last) {}
virtual ~basic_membuffer() = default;
basic_membuffer(const basic_membuffer&) = delete;
basic_membuffer& operator=(const basic_membuffer&) = delete;
size_t avail() const NOEXCEPT { return last_ - curr_; }
const Ty* curr() const NOEXCEPT { return curr_; }
Ty* curr() NOEXCEPT { return curr_; }
Ty** p_curr() NOEXCEPT { return &curr_; }
const Ty* last() const NOEXCEPT { return last_; }
Ty* last() NOEXCEPT { return last_; }
Ty& back() NOEXCEPT { return *(curr_ - 1); }
basic_membuffer& advance(size_t n) NOEXCEPT {
assert(n <= avail());
curr_ += n;
return *this;
}
template<typename InputIt, typename = std::enable_if_t<is_random_access_iterator<InputIt>::value>>
basic_membuffer& append_by_chunks(InputIt first, InputIt last) {
size_t count = last - first, n_avail = avail();
while (count > n_avail) {
curr_ = std::copy_n(first, n_avail, curr_);
if (!try_grow()) { return *this; }
first += n_avail, count -= n_avail;
n_avail = avail();
}
curr_ = std::copy(first, last, curr_);
return *this;
}
basic_membuffer& append_by_chunks(size_t count, Ty val) {
size_t n_avail = avail();
while (count > n_avail) {
curr_ = std::fill_n(curr_, n_avail, val);
if (!try_grow()) { return *this; }
count -= n_avail;
n_avail = avail();
}
curr_ = std::fill_n(curr_, count, val);
return *this;
}
template<typename InputIt, typename = std::enable_if_t<is_random_access_iterator<InputIt>::value>>
basic_membuffer& append(InputIt first, InputIt last) {
const size_t count = last - first;
if (avail() >= count || try_grow(count)) {
curr_ = std::copy(first, last, curr_);
return *this;
}
return append_by_chunks(first, last);
}
basic_membuffer& append(size_t count, Ty val) {
if (avail() >= count || try_grow(count)) {
curr_ = std::fill_n(curr_, count, val);
return *this;
}
return append_by_chunks(count, val);
}
template<typename... Args>
void emplace_back(Args&&... args) {
if (curr_ != last_ || try_grow()) { new (curr_++) Ty(std::forward<Args>(args)...); }
}
void push_back(Ty val) {
if (curr_ != last_ || try_grow()) { *curr_++ = val; }
}
void pop_back() { --curr_; }
template<typename Range, typename = std::void_t<decltype(std::declval<Range>().end())>>
basic_membuffer& operator+=(const Range& r) {
return append(r.begin(), r.end());
}
basic_membuffer& operator+=(const value_type* s) { return *this += std::basic_string_view<value_type>(s); }
basic_membuffer& operator+=(value_type ch) {
push_back(ch);
return *this;
}
virtual bool try_grow(size_t extra = 1) { return false; }
protected:
void set(Ty* curr) NOEXCEPT { curr_ = curr; }
void set(Ty* curr, Ty* last) NOEXCEPT { curr_ = curr, last_ = last; }
private:
Ty* curr_;
Ty* last_;
};
using membuffer = basic_membuffer<char>;
using wmembuffer = basic_membuffer<wchar_t>;
template<typename Ty, typename Alloc>
class basic_dynbuffer : protected std::allocator_traits<Alloc>::template rebind_alloc<Ty>, public basic_membuffer<Ty> {
private:
using alloc_type = typename std::allocator_traits<Alloc>::template rebind_alloc<Ty>;
public:
using value_type = typename basic_membuffer<Ty>::value_type;
~basic_dynbuffer() override {
if (is_allocated_) { this->deallocate(first_, capacity()); }
}
bool empty() const NOEXCEPT { return first_ == this->curr(); }
size_t size() const NOEXCEPT { return this->curr() - first_; }
size_t capacity() const NOEXCEPT { return this->last() - first_; }
const Ty* data() const NOEXCEPT { return first_; }
Ty* data() NOEXCEPT { return first_; }
void clear() NOEXCEPT { this->set(first_); }
void reserve(size_t extra = 1) {
if (extra > this->avail()) { try_grow(extra); }
}
bool try_grow(size_t extra) override {
size_t sz = size(), cap = capacity(), delta_sz = std::max(extra, sz >> 1);
const size_t max_avail = std::allocator_traits<alloc_type>::max_size(*this) - sz;
if (delta_sz > max_avail) {
if (extra > max_avail) { throw std::length_error("too much to reserve"); }
delta_sz = std::max(extra, max_avail >> 1);
}
sz += delta_sz;
Ty* first = this->allocate(sz);
this->set(std::copy(first_, this->curr(), first), first + sz);
if (is_allocated_) { this->deallocate(first_, cap); }
first_ = first, is_allocated_ = true;
return true;
}
protected:
basic_dynbuffer(Ty* first, Ty* last) NOEXCEPT : basic_membuffer<Ty>(first, last),
first_(first),
is_allocated_(false) {}
private:
Ty* first_;
bool is_allocated_;
};
template<typename Ty, size_t InlineBufSize = 0, typename Alloc = std::allocator<Ty>>
class inline_basic_dynbuffer final : public basic_dynbuffer<Ty, Alloc> {
public:
inline_basic_dynbuffer()
: basic_dynbuffer<Ty, Alloc>(reinterpret_cast<Ty*>(buf_), reinterpret_cast<Ty*>(&buf_[kInlineBufSize])) {}
private:
enum : unsigned {
#if defined(NDEBUG) || !defined(_DEBUG_REDUCED_BUFFERS)
kInlineBufSize = InlineBufSize != 0 ? InlineBufSize : 256 / sizeof(Ty)
#else // defined(NDEBUG) || !defined(_DEBUG_REDUCED_BUFFERS)
kInlineBufSize = 7
#endif // defined(NDEBUG) || !defined(_DEBUG_REDUCED_BUFFERS)
};
typename std::aligned_storage<sizeof(Ty), std::alignment_of<Ty>::value>::type buf_[kInlineBufSize];
};
using inline_dynbuffer = inline_basic_dynbuffer<char>;
using inline_wdynbuffer = inline_basic_dynbuffer<wchar_t>;
// --------------------------
template<typename StrTy, typename Func>
void append_adjusted(StrTy& s, Func fn, unsigned len, const fmt_opts& fmt) {
unsigned left = fmt.width - len, right = left;
if (!(fmt.flags & fmt_flags::kLeadingZeroes)) {
switch (fmt.flags & fmt_flags::kAdjustField) {
case fmt_flags::kRight: right = 0; break;
case fmt_flags::kInternal: left >>= 1, right -= left; break;
case fmt_flags::kLeft:
default: left = 0; break;
}
} else {
right = 0;
}
s.append(left, fmt.fill);
fn(s);
s.append(right, fmt.fill);
}
// --------------------------
namespace scvt {
template<typename Ty>
struct fp_traits;
template<>
struct fp_traits<double> {
static_assert(sizeof(double) == sizeof(uint64_t), "type size mismatch");
enum : unsigned { kTotalBits = 64, kBitsPerMantissa = 52 };
enum : uint64_t { kMantissaMask = (1ull << kBitsPerMantissa) - 1 };
enum : int { kExpMax = (1 << (kTotalBits - kBitsPerMantissa - 1)) - 1 };
static uint64_t to_u64(const double& f) { return *reinterpret_cast<const uint64_t*>(&f); }
static double from_u64(const uint64_t& u64) { return *reinterpret_cast<const double*>(&u64); }
};
template<>
struct fp_traits<float> {
static_assert(sizeof(float) == sizeof(uint32_t), "type size mismatch");
enum : unsigned { kTotalBits = 32, kBitsPerMantissa = 23 };
enum : uint64_t { kMantissaMask = (1ull << kBitsPerMantissa) - 1 };
enum : int { kExpMax = (1 << (kTotalBits - kBitsPerMantissa - 1)) - 1 };
static uint64_t to_u64(const float& f) { return *reinterpret_cast<const uint32_t*>(&f); }
static float from_u64(const uint64_t& u64) { return *reinterpret_cast<const float*>(&u64); }
};
extern UXS_EXPORT const fmt_opts g_default_opts;
// --------------------------
template<typename Ty, typename = void>
struct reduce_type {
using type = std::remove_cv_t<Ty>;
};
template<typename Ty>
struct reduce_type<Ty, std::enable_if_t<std::is_integral<Ty>::value && std::is_unsigned<Ty>::value &&
!is_boolean<Ty>::value && !is_character<Ty>::value>> {
using type = std::conditional_t<(sizeof(Ty) <= sizeof(uint32_t)), uint32_t, uint64_t>;
};
template<typename Ty>
struct reduce_type<Ty, std::enable_if_t<std::is_integral<Ty>::value && std::is_signed<Ty>::value &&
!is_boolean<Ty>::value && !is_character<Ty>::value>> {
using type = std::conditional_t<(sizeof(Ty) <= sizeof(int32_t)), int32_t, int64_t>;
};
template<typename Ty>
struct reduce_type<Ty, std::enable_if_t<std::is_array<Ty>::value>> {
using type = typename std::add_pointer<std::remove_cv_t<typename std::remove_extent<Ty>::type>>::type;
};
template<typename Ty>
struct reduce_type<Ty*, void> {
using type = typename std::add_pointer<std::remove_cv_t<Ty>>::type;
};
template<>
struct reduce_type<std::nullptr_t, void> {
using type = void*;
};
template<typename Ty>
using reduce_type_t = typename reduce_type<Ty>::type;
// --------------------------
template<typename Ty, typename CharT>
UXS_EXPORT Ty to_integral_common(const CharT* p, const CharT* end, const CharT*& last, Ty pos_limit) NOEXCEPT;
template<typename CharT>
UXS_EXPORT uint64_t to_float_common(const CharT* p, const CharT* end, const CharT*& last, const unsigned bpm,
const int exp_max) NOEXCEPT;
template<typename Ty, typename CharT>
UXS_EXPORT Ty to_bool(const CharT* p, const CharT* end, const CharT*& last) NOEXCEPT;
template<typename Ty, typename CharT>
Ty to_integral(const CharT* p, const CharT* end, const CharT*& last) NOEXCEPT {
using UTy = typename std::make_unsigned<Ty>::type;
return static_cast<Ty>(to_integral_common<reduce_type_t<UTy>>(p, end, last, std::numeric_limits<UTy>::max()));
}
template<typename Ty, typename CharT>
Ty to_char(const CharT* p, const CharT* end, const CharT*& last) NOEXCEPT {
last = p;
if (p == end) { return '\0'; }
++last;
return *p;
}
template<typename Ty, typename CharT>
Ty to_float(const CharT* p, const CharT* end, const CharT*& last) NOEXCEPT {
using FpTy = std::conditional_t<(sizeof(Ty) <= sizeof(double)), Ty, double>;
return static_cast<Ty>(fp_traits<FpTy>::from_u64(
to_float_common(p, end, last, fp_traits<FpTy>::kBitsPerMantissa, fp_traits<FpTy>::kExpMax)));
}
// --------------------------
template<typename CharT, typename Ty>
UXS_EXPORT void fmt_integral_common(basic_membuffer<CharT>& s, Ty val, const fmt_opts& fmt);
template<typename CharT, typename Ty>
UXS_EXPORT void fmt_char(basic_membuffer<CharT>& s, Ty val, const fmt_opts& fmt);
template<typename CharT, typename Ty>
UXS_EXPORT void fmt_bool(basic_membuffer<CharT>& s, Ty val, const fmt_opts& fmt);
template<typename CharT>
UXS_EXPORT void fmt_float_common(basic_membuffer<CharT>& s, uint64_t u64, const fmt_opts& fmt, const unsigned bpm,
const int exp_max);
template<typename CharT, typename Ty>
void fmt_integral(basic_membuffer<CharT>& s, Ty val, const fmt_opts& fmt) {
fmt_integral_common(s, static_cast<reduce_type_t<Ty>>(val), fmt);
}
template<typename CharT, typename Ty>
void fmt_float(basic_membuffer<CharT>& s, Ty val, const fmt_opts& fmt) {
using FpTy = std::conditional_t<(sizeof(Ty) <= sizeof(double)), Ty, double>;
fmt_float_common(s, fp_traits<Ty>::to_u64(static_cast<FpTy>(val)), fmt, fp_traits<Ty>::kBitsPerMantissa,
fp_traits<Ty>::kExpMax);
}
} // namespace scvt
// --------------------------
template<typename Ty, typename CharT>
struct string_parser;
template<typename Ty, typename CharT>
struct formatter;
namespace detail {
template<typename Ty, typename CharT>
struct has_string_parser {
template<typename U>
static auto test(const U* first, const U* last, Ty& v)
-> std::is_same<decltype(string_parser<Ty, U>().from_chars(first, last, v)), const U*>;
template<typename U>
static auto test(...) -> std::false_type;
using type = decltype(test<CharT>(nullptr, nullptr, std::declval<Ty&>()));
};
template<typename Ty, typename StrTy>
struct has_formatter {
template<typename U>
static auto test(U& s, const Ty& v)
-> always_true<decltype(formatter<Ty, typename U::value_type>().format(s, v, fmt_opts{}))>;
template<typename U>
static auto test(...) -> std::false_type;
using type = decltype(test<StrTy>(std::declval<StrTy&>(), std::declval<Ty>()));
};
} // namespace detail
template<typename Ty, typename CharT = char>
struct has_string_parser : detail::has_string_parser<Ty, CharT>::type {};
template<typename Ty, typename StrTy = membuffer>
struct has_formatter : detail::has_formatter<Ty, StrTy>::type {};
#define UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(ty, from_chars_func, fmt_func) \
template<typename CharT> \
struct string_parser<ty, CharT> { \
const CharT* from_chars(const CharT* first, const CharT* last, ty& val) const NOEXCEPT { \
auto t = scvt::from_chars_func<ty>(first, last, last); \
if (last != first) { val = t; } \
return last; \
} \
}; \
template<typename CharT> \
struct formatter<ty, CharT> { \
template<typename StrTy, typename = std::enable_if_t<!std::is_base_of<basic_membuffer<CharT>, StrTy>::value>> \
void format(StrTy& s, ty val, const fmt_opts& fmt) const { \
inline_basic_dynbuffer<CharT> buf; \
format(buf, val, fmt); \
s.append(buf.data(), buf.data() + buf.size()); \
} \
void format(basic_membuffer<CharT>& s, ty val, const fmt_opts& fmt) const { \
scvt::fmt_func<CharT, ty>(s, val, fmt); \
} \
};
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(unsigned char, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(unsigned short, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(unsigned, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(unsigned long, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(unsigned long long, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(signed char, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(signed short, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(signed, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(signed long, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(signed long long, to_integral, fmt_integral)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(CharT, to_char, fmt_char)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(bool, to_bool, fmt_bool)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(float, to_float, fmt_float)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(double, to_float, fmt_float)
UXS_SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER(long double, to_float, fmt_float)
#undef SCVT_IMPLEMENT_STANDARD_STRING_CONVERTER
template<typename Ty>
const char* from_chars(const char* first, const char* last, Ty& v) {
return string_parser<Ty, char>().from_chars(first, last, v);
}
template<typename Ty>
const wchar_t* from_wchars(const wchar_t* first, const wchar_t* last, Ty& v) {
return string_parser<Ty, wchar_t>().from_chars(first, last, v);
}
template<typename Ty, typename CharT, typename Traits = std::char_traits<CharT>>
size_t basic_stoval(std::basic_string_view<CharT, Traits> s, Ty& v) {
return string_parser<Ty, CharT>().from_chars(s.data(), s.data() + s.size(), v) - s.data();
}
template<typename Ty>
size_t stoval(std::string_view s, Ty& v) {
return basic_stoval(s, v);
}
template<typename Ty>
size_t wstoval(std::wstring_view s, Ty& v) {
return basic_stoval(s, v);
}
template<typename Ty, typename CharT, typename Traits = std::char_traits<CharT>>
NODISCARD Ty from_basic_string(std::basic_string_view<CharT, Traits> s) {
Ty result{};
basic_stoval(s, result);
return result;
}
template<typename Ty>
NODISCARD Ty from_string(std::string_view s) {
return from_basic_string<Ty>(s);
}
template<typename Ty>
NODISCARD Ty from_wstring(std::wstring_view s) {
return from_basic_string<Ty>(s);
}
template<typename StrTy, typename Ty>
StrTy& to_basic_string(StrTy& s, const Ty& val, const fmt_opts& fmt = scvt::g_default_opts) {
formatter<Ty, typename StrTy::value_type>().format(s, val, fmt);
return s;
}
template<typename Ty>
NODISCARD std::string to_string(const Ty& val) {
inline_dynbuffer buf;
to_basic_string(buf, val);
return std::string(buf.data(), buf.size());
}
template<typename Ty, typename... Opts>
NODISCARD std::string to_string(const Ty& val, const Opts&... opts) {
inline_dynbuffer buf;
to_basic_string(buf, val, fmt_opts(opts...));
return std::string(buf.data(), buf.size());
}
template<typename Ty>
NODISCARD std::wstring to_wstring(const Ty& val) {
inline_wdynbuffer buf;
to_basic_string(buf, val);
return std::wstring(buf.data(), buf.size());
}
template<typename Ty, typename... Opts>
NODISCARD std::wstring to_wstring(const Ty& val, const Opts&... opts) {
inline_wdynbuffer buf;
to_basic_string(buf, val, fmt_opts(opts...));
return std::wstring(buf.data(), buf.size());
}
template<typename Ty>
char* to_chars(char* p, const Ty& val) {
membuffer buf(p);
return to_basic_string(buf, val).curr();
}
template<typename Ty, typename... Opts>
char* to_chars(char* p, const Ty& val, const Opts&... opts) {
membuffer buf(p);
return to_basic_string(buf, val, fmt_opts(opts...)).curr();
}
template<typename Ty>
wchar_t* to_wchars(wchar_t* p, const Ty& val) {
wmembuffer buf(p);
return to_basic_string(buf, val).curr();
}
template<typename Ty, typename... Opts>
wchar_t* to_wchars(wchar_t* p, const Ty& val, const Opts&... opts) {
wmembuffer buf(p);
return to_basic_string(buf, val, fmt_opts(opts...)).curr();
}
template<typename Ty>
char* to_chars_n(char* p, size_t n, const Ty& val) {
membuffer buf(p, p + n);
return to_basic_string(buf, val).curr();
}
template<typename Ty, typename... Opts>
char* to_chars_n(char* p, size_t n, const Ty& val, const Opts&... opts) {
membuffer buf(p, p + n);
return to_basic_string(buf, val, fmt_opts(opts...)).curr();
}
template<typename Ty>
wchar_t* to_wchars_n(wchar_t* p, size_t n, const Ty& val) {
wmembuffer buf(p, p + n);
return to_basic_string(buf, val).curr();
}
template<typename Ty, typename... Opts>
wchar_t* to_wchars_n(wchar_t* p, size_t n, const Ty& val, const Opts&... opts) {
wmembuffer buf(p, p + n);
return to_basic_string(buf, val, fmt_opts(opts...)).curr();
}
} // namespace uxs
|
<?php
namespace App\Http\Controllers;
use App\Models\Subscription;
use App\Models\SubscriptionPlan;
use App\Models\UserTransaction;
use App\Repositories\SubscriptionPlanRepository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Arr;
use Laracasts\Flash\Flash;
class SubscriptionPricingPlanController extends Controller
{
private SubscriptionPlanRepository $subscriptionPlanRepository;
public function __construct(SubscriptionPlanRepository $subscriptionPlanRepo)
{
$this->subscriptionPlanRepository = $subscriptionPlanRepo;
}
/**
* @return Application|Factory|View
*/
public function index(): \Illuminate\View\View
{
$data = $this->subscriptionPlanRepository->getSubscriptionPlansData();
return view('subscription_pricing_plans.index')->with($data);
}
public function choosePaymentType($planId, $context = null, $fromScreen = null)
{
// code for checking the current plan is active or not, if active then it should not allow to choose that plan
$subscription = getSubscription();
if ($subscription->subscriptionPlan->id == $planId) {
$toastData = [
'toastType' => 'warning',
'toastMessage' => $subscription->subscriptionPlan->name.' '.__('messages.subscription_pricing_plans.has_already_been_subscribed'),
];
if ($context != null && $context == 'landing') {
if ($fromScreen == 'landing.home') {
return redirect(route('landing.home'))->with('toast-data', $toastData);
} elseif ($fromScreen == 'landing.about.us') {
return redirect(route('landing.about.us'))->with('toast-data', $toastData);
} elseif ($fromScreen == 'landing.services') {
return redirect(route('landing.services'))->with('toast-data', $toastData);
} elseif ($fromScreen == 'landing.pricing') {
return redirect(route('landing.pricing'))->with('toast-data', $toastData);
}
}
}
$subscriptionsPricingPlan = SubscriptionPlan::find($planId);
$paymentTypes = Arr::except(Subscription::PAYMENT_TYPES, [Subscription::TYPE_FREE]);
$paymentTypes = Arr::except($paymentTypes, 0);
$userSetting = getUserSettingData(getLogInUserId());
$userTransaction = UserTransaction::whereUserId(getLogInUserId())
->wherePaymentType(UserTransaction::MANUALLY)
->whereSubscriptionStatus(UserTransaction::PENDING)
->latest()->exists();
if ($userTransaction) {
Flash::error(__('messages.cash_payment.manual_transaction_requests_pending'));
return redirect(route('subscription.pricing.plans.index'));
}
return view('subscription_pricing_plans.payment_for_plan', compact('subscriptionsPricingPlan', 'paymentTypes', 'userSetting'));
}
}
|
//
// FlowNavigationStackV2.swift
//
//
// Created by Gerardo Grisolini on 13/10/22.
//
import SwiftUI
import Combine
import Resolver
public class FlowNavigationStackV2: ObservableObject {
@Injected var navigation: NavigationProtocol
@Published public var routes: [String] = []
@Published public var presentedView: (any View)? = nil
private var cancellables = Set<AnyCancellable>()
public init() {
routes = navigation.routes
navigation.action
.eraseToAnyPublisher()
.receive(on: DispatchQueue.main)
.sink { [weak self] action in
self?.onChange(action: action)
}
.store(in: &cancellables)
}
func view(route: String) -> AnyView? {
guard let view = navigation.items[route]?() else { return nil }
guard let page = view as? any View else {
#if canImport(UIKit)
guard let vc = view as? UIViewController else {
return nil
}
return AnyView(vc.toSwiftUI().navigationTitle(vc.title ?? ""))
#else
return nil
#endif
}
return AnyView(page)
}
private func navigate(route: String) {
guard routes.last != route else { return }
routes.append(route)
}
private func pop(route: String) {
guard routes.last == route else { return }
routes.removeLast()
}
private func popToRoot() {
routes = []
}
private func onChange(action: NavigationAction) {
switch action {
case .navigate(route: let route):
navigate(route: route)
case .pop(route: let route):
pop(route: route)
case .popToRoot:
popToRoot()
case .present(let route):
guard let page = navigation.items[route]?() as? any View else {
#if canImport(UIKit)
guard let page = navigation.items[route]?() as? UIViewController else {
return
}
presentedView = page.toSwiftUI()
#endif
return
}
presentedView = page
case .dismiss:
presentedView = nil
}
}
}
|
import 'package:expense_tracker/custom_widgets/custom_button.dart';
import 'package:expense_tracker/custom_widgets/custom_dropfield.dart';
import 'package:expense_tracker/custom_widgets/custom_spacing.dart';
import 'package:expense_tracker/custom_widgets/custom_textfield.dart';
import 'package:expense_tracker/custom_widgets/custom_toast.dart';
import 'package:expense_tracker/service/networking_service/network_status_check.dart';
import 'package:expense_tracker/utils/form_validators.dart';
import 'package:expense_tracker/utils/transaction_helper.dart';
import 'package:expense_tracker/viewmodels/income_viewmodel.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class AddIncomeView extends StatelessWidget with Validators {
AddIncomeView({super.key});
final _formKey = GlobalKey<FormState>();
final TextEditingController nameController = TextEditingController();
final TextEditingController amountController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Add Income",
)),
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomDropField(
controller: nameController,
title: "Name of Revenue",
onValidate: Validators.validateFieldEmpty,
selectedItem: (selectedItem) {},
options: TransactionType.incomeTransactions,
),
CustomTextField(
controller: amountController,
textInputType: TextInputType.number,
textfieldLabel: "Amount",
validator: Validators.validateFieldEmpty),
const YMargin(40),
Consumer<IncomeViewmodel>(
builder: ((context, incomeViewmodel, child) {
return CustomButton(
isLoading: isApiResponseLoading(
incomeViewmodel.saveIncomeResponse),
title: "Save Income",
onTap: () async {
if (_formKey.currentState!.validate()) {
await incomeViewmodel.saveIncome(
nameOfRevenue: nameController.text.trim(),
amount: double.tryParse(
amountController.text.trim()) ??
0);
if (isApiResponseCompleted(
incomeViewmodel.saveIncomeResponse)) {
showToast(
incomeViewmodel.saveIncomeResponse.data!,
);
// ignore: use_build_context_synchronously
Navigator.pop(context);
} else if (isApiResponseError(
incomeViewmodel.saveIncomeResponse)) {
showToast(
incomeViewmodel.saveIncomeResponse.message,
isError: true);
}
}
});
}))
],
),
),
),
),
),
);
}
}
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { RootState } from '../store/store';
export interface UserInterface {
id: string,
name: string,
room: string,
type: 'cpu' | 'human',
}
export interface UsersState {
users: UserInterface[],
}
const initialState: UsersState = {
users: [],
};
/* eslint-disable no-param-reassign */
export const usersSlice = createSlice({
name: 'users',
initialState,
reducers: {
setUsers: (state, action: PayloadAction<UserInterface[]>) => {
state.users = action.payload;
},
},
});
/* eslint-enable no-param-reassign */
export const { setUsers } = usersSlice.actions;
export const selectUsers = (state: RootState) => state.users;
export default usersSlice.reducer;
|
<h1>Sign Up Page</h1>
<%= form_with(model: @user,url: sign_up_path, data: { turbo: false }) do |form|%>
<div>
<% @user.errors.full_messages.each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div class="form-outline mb-4">
<%= form.label :username%>
<%= form.text_field :username, class: "form-control",placeholder: "Enter username"%>
</div>
<div class="form-outline mb-4">
<%= form.label :email%>
<%= form.text_field :email, class: "form-control",placeholder: "Enter email"%>
</div>
<div class="form-outline mb-4">
<%= form.label :password%>
<%= form.password_field :password, class: "form-control",placeholder: "Enter password"%>
</div>
<div class="form-outline mb-4">
<%= form.label :password_confirmation%>
<%= form.password_field :password_confirmation, class: "form-control",placeholder: "confirm password"%>
</div>
<div>
<%= form.submit :SignUp, class: "btn btn-primary" %>
</div>
<%end%>
|
public class Individual {
private boolean[] chromosome;
private double fitness = -1;
private KnapsackProblem problem;
public Individual(KnapsackProblem problem) {
this.problem = problem;
this.chromosome = new boolean[problem.getItems().size()];
}
public void generateIndividual() {
for (int geneIndex = 0; geneIndex < this.chromosome.length; geneIndex++) {
this.chromosome[geneIndex] = Math.random() > 0.5;
}
}
public boolean[] getChromosome() {
return this.chromosome;
}
public boolean getGene(int index) {
return this.chromosome[index];
}
public void setGene(int index, boolean value) {
this.chromosome[index] = value;
}
public int getChromosomeLength() {
return this.chromosome.length;
}
public void calcFitness() {
int totalWeight = 0;
int totalValue = 0;
for (int geneIndex = 0; geneIndex < this.chromosome.length; geneIndex++) {
if (getGene(geneIndex)) {
totalWeight += problem.getItems().get(geneIndex).getWeight();
totalValue += problem.getItems().get(geneIndex).getValue();
}
}
if (totalWeight > problem.getMaxWeight()) {
this.fitness = 0;
} else {
this.fitness = totalValue;
}
}
public double getFitness() {
return this.fitness;
}
@Override
public String toString() {
StringBuilder chromosomeString = new StringBuilder();
for (boolean gene : chromosome) {
chromosomeString.append(gene ? "1" : "0");
}
return String.format("Cromozom: %s, Fitness: %.2f", chromosomeString.toString(), getFitness());
}
}
|
use async_stream::stream;
use dogbox_tree_editor::DirectoryEntryKind;
use dogbox_tree_editor::NormalizedPath;
use dogbox_tree_editor::OpenFile;
use futures::stream::StreamExt;
use std::sync::Arc;
use tracing::error;
use tracing::info;
#[derive(Clone)]
pub struct DogBoxFileSystem {
editor: Arc<dogbox_tree_editor::TreeEditor>,
}
impl DogBoxFileSystem {
pub fn new(editor: dogbox_tree_editor::TreeEditor) -> DogBoxFileSystem {
DogBoxFileSystem {
editor: Arc::new(editor),
}
}
}
#[derive(Debug, Clone)]
struct DogBoxDirectoryMetaData {}
impl dav_server::fs::DavMetaData for DogBoxDirectoryMetaData {
fn len(&self) -> u64 {
0
}
fn modified(&self) -> dav_server::fs::FsResult<std::time::SystemTime> {
Ok(std::time::SystemTime::now())
}
fn is_dir(&self) -> bool {
true
}
}
#[derive(Debug, Clone)]
struct DogBoxMetaData {
kind: DirectoryEntryKind,
}
impl dav_server::fs::DavMetaData for DogBoxMetaData {
fn len(&self) -> u64 {
match self.kind {
DirectoryEntryKind::Directory => 0,
DirectoryEntryKind::File(length) => length,
}
}
fn modified(&self) -> dav_server::fs::FsResult<std::time::SystemTime> {
Ok(std::time::SystemTime::now())
}
fn is_dir(&self) -> bool {
match self.kind {
DirectoryEntryKind::Directory => true,
DirectoryEntryKind::File(_) => false,
}
}
}
#[derive(Debug, Clone)]
struct DogBoxFileMetaData {
size: u64,
}
impl dav_server::fs::DavMetaData for DogBoxFileMetaData {
fn len(&self) -> u64 {
self.size
}
fn modified(&self) -> dav_server::fs::FsResult<std::time::SystemTime> {
Ok(std::time::SystemTime::now())
}
fn is_dir(&self) -> bool {
false
}
}
struct DogBoxDirEntry {
info: dogbox_tree_editor::DirectoryEntry,
}
impl dav_server::fs::DavDirEntry for DogBoxDirEntry {
fn name(&self) -> Vec<u8> {
self.info.name.as_bytes().into()
}
fn metadata(&self) -> dav_server::fs::FsFuture<Box<dyn dav_server::fs::DavMetaData>> {
let result = match self.info.kind {
dogbox_tree_editor::DirectoryEntryKind::Directory => {
Box::new(DogBoxDirectoryMetaData {})
as Box<(dyn dav_server::fs::DavMetaData + 'static)>
}
dogbox_tree_editor::DirectoryEntryKind::File(size) => {
Box::new(DogBoxFileMetaData { size: size })
as Box<(dyn dav_server::fs::DavMetaData + 'static)>
}
};
Box::pin(async move { Ok(result) })
}
}
#[derive(Debug)]
struct DogBoxOpenFile {
handle: Arc<OpenFile>,
cursor: u64,
}
impl dav_server::fs::DavFile for DogBoxOpenFile {
fn metadata(&mut self) -> dav_server::fs::FsFuture<Box<dyn dav_server::fs::DavMetaData>> {
Box::pin(async move {
Ok(Box::new(DogBoxMetaData {
kind: self.handle.get_meta_data().await,
}) as Box<(dyn dav_server::fs::DavMetaData)>)
})
}
fn write_buf(&mut self, _buf: Box<dyn bytes::Buf + Send>) -> dav_server::fs::FsFuture<()> {
todo!()
}
fn write_bytes(&mut self, buf: bytes::Bytes) -> dav_server::fs::FsFuture<()> {
let write_at = self.cursor;
self.cursor += buf.len() as u64;
let open_file = self.handle.clone();
Box::pin(async move {
match open_file.write_bytes(write_at, buf).await {
Ok(result) => Ok(result),
Err(error) => match error {
dogbox_tree_editor::Error::NotFound => todo!(),
dogbox_tree_editor::Error::CannotOpenRegularFileAsDirectory => todo!(),
dogbox_tree_editor::Error::CannotOpenDirectoryAsRegularFile => todo!(),
},
}
})
}
fn read_bytes(&mut self, count: usize) -> dav_server::fs::FsFuture<bytes::Bytes> {
let read_at = self.cursor;
self.cursor += count as u64;
let open_file = self.handle.clone();
Box::pin(async move {
match open_file.read_bytes(read_at, count).await {
Ok(result) => Ok(result),
Err(error) => match error {
dogbox_tree_editor::Error::NotFound => todo!(),
dogbox_tree_editor::Error::CannotOpenRegularFileAsDirectory => todo!(),
dogbox_tree_editor::Error::CannotOpenDirectoryAsRegularFile => todo!(),
},
}
})
}
fn seek(&mut self, _pos: std::io::SeekFrom) -> dav_server::fs::FsFuture<u64> {
todo!()
}
fn flush(&mut self) -> dav_server::fs::FsFuture<()> {
self.handle.flush();
Box::pin(std::future::ready(Ok(())))
}
}
fn convert_path<'t>(
path: &'t dav_server::davpath::DavPath,
) -> dav_server::fs::FsResult<&'t relative_path::RelativePath> {
match relative_path::RelativePath::from_path(path.as_rel_ospath()) {
Ok(success) => Ok(success),
Err(error) => {
error!(
"Could not convert path {} into a relative path: {}",
path, error
);
Err(dav_server::fs::FsError::GeneralFailure)
}
}
}
impl dav_server::fs::DavFileSystem for DogBoxFileSystem {
fn open<'a>(
&'a self,
path: &'a dav_server::davpath::DavPath,
options: dav_server::fs::OpenOptions,
) -> dav_server::fs::FsFuture<Box<dyn dav_server::fs::DavFile>> {
info!("Open {} | {:?}", path, options);
Box::pin(async move {
let converted_path = convert_path(&path)?;
let open_file = match self
.editor
.open_file(NormalizedPath::new(converted_path))
.await
{
Ok(success) => success,
Err(_error) => todo!(),
};
Ok(Box::new(DogBoxOpenFile {
handle: open_file,
cursor: 0,
}) as Box<dyn dav_server::fs::DavFile>)
})
}
fn read_dir<'a>(
&'a self,
path: &'a dav_server::davpath::DavPath,
_meta: dav_server::fs::ReadDirMeta,
) -> dav_server::fs::FsFuture<dav_server::fs::FsStream<Box<dyn dav_server::fs::DavDirEntry>>>
{
info!("Read dir {}", path);
Box::pin(async move {
let converted_path = convert_path(&path)?;
let mut directory = match self
.editor
.read_directory(NormalizedPath::new(converted_path))
.await
{
Ok(success) => success,
Err(error) => match error {
dogbox_tree_editor::Error::NotFound => {
info!("Directory not found: {}", converted_path);
return Err(dav_server::fs::FsError::NotFound);
}
dogbox_tree_editor::Error::CannotOpenRegularFileAsDirectory => {
info!(
"Cannot open regular file as a directory: {}",
converted_path
);
return Err(dav_server::fs::FsError::NotImplemented);
}
dogbox_tree_editor::Error::CannotOpenDirectoryAsRegularFile => todo!(),
},
};
Ok(Box::pin(stream! {
while let Some(entry) = directory.next().await {
info!("Directory entry {:?}", entry);
yield (Box::new(DogBoxDirEntry{info: entry,}) as Box<dyn dav_server::fs::DavDirEntry>);
}
})
as dav_server::fs::FsStream<
Box<dyn dav_server::fs::DavDirEntry>,
>)
})
}
fn metadata<'a>(
&'a self,
path: &'a dav_server::davpath::DavPath,
) -> dav_server::fs::FsFuture<Box<dyn dav_server::fs::DavMetaData>> {
info!("Metadata {}", path);
Box::pin(async move {
let converted_path = convert_path(&path)?;
match self
.editor
.get_meta_data(NormalizedPath::new(converted_path))
.await
{
Ok(success) => Ok(Box::new(DogBoxMetaData { kind: success })
as Box<(dyn dav_server::fs::DavMetaData + 'static)>),
Err(error) => match error {
dogbox_tree_editor::Error::NotFound => {
info!("File or directory not found: {}", converted_path);
return Err(dav_server::fs::FsError::NotFound);
}
dogbox_tree_editor::Error::CannotOpenRegularFileAsDirectory => {
info!(
"Cannot read regular file as a directory: {}",
converted_path
);
return Err(dav_server::fs::FsError::NotImplemented);
}
dogbox_tree_editor::Error::CannotOpenDirectoryAsRegularFile => todo!(),
},
}
})
}
fn symlink_metadata<'a>(
&'a self,
path: &'a dav_server::davpath::DavPath,
) -> dav_server::fs::FsFuture<Box<dyn dav_server::fs::DavMetaData>> {
self.metadata(path)
}
fn create_dir<'a>(
&'a self,
path: &'a dav_server::davpath::DavPath,
) -> dav_server::fs::FsFuture<()> {
info!("Create directory {}", path);
Box::pin(async move {
let converted_path = convert_path(&path)?;
match self
.editor
.create_directory(NormalizedPath::new(converted_path))
.await
{
Ok(success) => Ok(success),
Err(error) => match error {
dogbox_tree_editor::Error::NotFound => {
info!("File or directory not found: {}", converted_path);
return Err(dav_server::fs::FsError::NotFound);
}
dogbox_tree_editor::Error::CannotOpenRegularFileAsDirectory => {
info!(
"Cannot read regular file as a directory: {}",
converted_path
);
return Err(dav_server::fs::FsError::NotImplemented);
}
dogbox_tree_editor::Error::CannotOpenDirectoryAsRegularFile => todo!(),
},
}
})
}
fn remove_dir<'a>(
&'a self,
_path: &'a dav_server::davpath::DavPath,
) -> dav_server::fs::FsFuture<()> {
todo!()
}
fn remove_file<'a>(
&'a self,
_path: &'a dav_server::davpath::DavPath,
) -> dav_server::fs::FsFuture<()> {
todo!()
}
fn rename<'a>(
&'a self,
_from: &'a dav_server::davpath::DavPath,
_to: &'a dav_server::davpath::DavPath,
) -> dav_server::fs::FsFuture<()> {
todo!()
}
fn copy<'a>(
&'a self,
_from: &'a dav_server::davpath::DavPath,
_to: &'a dav_server::davpath::DavPath,
) -> dav_server::fs::FsFuture<()> {
todo!()
}
fn have_props<'a>(
&'a self,
_path: &'a dav_server::davpath::DavPath,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>> {
Box::pin(std::future::ready(false))
}
fn patch_props<'a>(
&'a self,
_path: &'a dav_server::davpath::DavPath,
_patch: Vec<(bool, dav_server::fs::DavProp)>,
) -> dav_server::fs::FsFuture<Vec<(hyper::StatusCode, dav_server::fs::DavProp)>> {
todo!()
}
fn get_props<'a>(
&'a self,
_path: &'a dav_server::davpath::DavPath,
_do_content: bool,
) -> dav_server::fs::FsFuture<Vec<dav_server::fs::DavProp>> {
todo!()
}
fn get_prop<'a>(
&'a self,
_path: &'a dav_server::davpath::DavPath,
_prop: dav_server::fs::DavProp,
) -> dav_server::fs::FsFuture<Vec<u8>> {
todo!()
}
fn get_quota(&self) -> dav_server::fs::FsFuture<(u64, Option<u64>)> {
todo!()
}
}
|
using CitiesManager.WebAPI.DataBaseContext;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace CitiesManager.WebAPI.Controllers.v2
{
[ApiVersion("2.0")]
public class CitiesController : CustomControllerBase
{
private readonly ApplicationDbContext _context;
public CitiesController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/Cities
/// <summary>
/// To get list of cities city names from 'cities' table
/// </summary>
/// <returns></returns>
[HttpGet]
// [Produces("application/xml")]
public async Task<ActionResult<IEnumerable<string?>>> GetCities()
{
if (_context.Cities == null)
{
return NotFound();
}
return await _context
.Cities
.OrderBy(city => city.CityName)
.Select(city => city.CityName)
.ToListAsync();
}
}
}
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getxmvvm/Resources/getx_localization/languages.dart';
import 'package:getxmvvm/Resources/routes/Routes.dart';
import 'package:getxmvvm/View/SplashScreen/SplashScreen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
debugShowCheckedModeBanner: false,
locale: const Locale('en', 'US'),
fallbackLocale: const Locale('en', 'US'),
translations: Languages(),
home: const SplashScreen(),
getPages: AppRoutes.appRoutes(),
);
}
}
|
import React, { useEffect, useState } from "react";
import axios from "axios";
import { Link, useNavigate } from "react-router-dom";
import { useForm } from "react-hook-form";
import classNames from "classnames";
import Starlogo from "../../assets/img/logo.png";
import { Button } from "rsuite";
import "rsuite/dist/rsuite.min.css";
import Navbar from "../Homepage/Navbar";
import { userPassword } from "../../atom";
import { useRecoilValue, useSetRecoilState } from "recoil";
import Footer from "../Footer/Footer";
const UserLoginPass = ({ otpEmail }) => {
const [loader, setLoader] = useState(false);
const navigate = useNavigate();
const Swal = require("sweetalert2");
const apiUrl = `${process.env.REACT_APP_APIENDPOINTNEW}user/login`;
let email = localStorage.getItem("userEmail");
const setPass = useSetRecoilState(userPassword);
const password = useRecoilValue(userPassword);
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const onSubmit = async (data) => {
setLoader(true);
await axios
.post(apiUrl, {
email: email,
password: data.password,
})
.then((res) => {
if (res?.data.message === "Logged In") {
setLoader(false);
setPass(data?.password);
localStorage.setItem("token-user", res?.data?.results.token);
localStorage.setItem(
"UserData",
JSON.stringify(res?.data?.results?.verifyUser)
);
Swal.fire({
title: "You have been successfully Logged In .",
icon: "success",
showCloseButton: true,
focusConfirm: false,
timer:1000
});
navigate("/app/home");
}
if (res?.data.message === "Your ID in under review") {
setLoader(false);
Swal.fire({
title: "Your ID in under review",
text: "Do you want to continue",
icon: "error",
confirmButtonText: "Cool",
});
}
if (res?.data.message === "You are suspended by admin") {
setLoader(false);
Swal.fire({
title: "Your Account has beed disabled. Please Contact Admin!",
width: 600,
icon: "error",
confirmButtonText: "Ok",
});
}
if (res?.data.message === "Wrong Password") {
setLoader(false);
Swal.fire({
title: "Wrong or Invalid Password!",
width: 600,
text: "Try again or click ‘Forgot password’ to reset it.",
icon: "error",
confirmButtonText: "Try again",
timer:2000
});
}
if (res?.data.message === "First Time Login") {
setLoader(false);
navigate("/app/update-password", { state: email });
}
});
};
const togglePassword = () => {
let x = document.getElementById("Password-2");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
};
return (
<div>
<Navbar />
<div class="login-new-design comman_padding marginTopLog">
<div class="container px-4 py-0">
<div class="row comman_divvision justify-content-center text-center">
<div class="col-12 login-new-img mb-lg-4 mb-md-4">
<img src={Starlogo} alt="" />
</div>
<div class="col-12 login-new-heading mb-4">
<h2>Welcome to StarImporters.</h2>
<span>Enter Your Password</span>
</div>
<div class="col-lg-6 col-md-8">
<form
class="row login-new-form"
action=""
onSubmit={handleSubmit(onSubmit)}
>
<div class="form-group mb-2 col-12">
<input
type="password"
className={classNames(
"form-control border border-secondary px-3",
{ "is-invalid": errors.password }
)}
id="Password-2"
placeholder="**********"
name="password"
{...register("password", {
required: "Enter Your Password",
})}
/>
<input
type="checkbox"
onClick={togglePassword}
className="showPassCheck"
/>
<small className=" showPass">Show Password</small>
</div>
<div class="form-group mb-4 pt-3 col-12">
<Button
loading={loader}
style={{ backgroundColor: "#eb3237" }}
appearance="primary"
type="submit"
className="new---btn"
>
Sign In
</Button>
</div>
<div className="form-group">
<Link
to="/app/forgot-password"
className="text-decoration-none text-primary"
style={{ fontSize: "14px" }}
>
Forgot Your Password?
</Link>
</div>
<div class="form-group mb-4 col-12">
<div class="forrm-btm">
Don’t have an account?{" "}
<a
className="text-decoration-none"
onClick={() => navigate("/app/register")}
>
Register Now
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<Footer/>
</div>
);
};
export default UserLoginPass;
|
---
title: "What is a Neural Network? Visualising & Understanding a Neural Network In-depth."
date: 2020-04-22 00:20:28
published: true
math: true
---
In this article, we will discuss the history, current usage, and development of Neural Networks. We will try to understand each of the segments while visualizing them.
This article aims to introduce neural networks in a manner that will require little to no prerequisites from the reader about the topics.
## **Chapter 1: Introduction to Neural Networks**
### **Part 1: PERCEPTRONS**
#### **1.0 VISUALISING PERCEPTRON**
It all started in 1958 with the invention of ***Perceptron***. It was an algorithm that was used to mimic the *biological neuron*. A perceptron was a type of ***Artificial Neuron.***
You might have seen the following figure in your school biology textbooks. So, what does it have to do with perceptron?!
*Let’s see how a* *perceptron* *relates to a* *biological neuron.*

If you observe the above image you will notice quite some similarities between a biological neuron and an artificial neuron.
> *Both take some input from the left-hand side and then process the data(applying the logic) in the middle part of it and then produces an output.*
Take a look at the above animation for 2-3 iterations and you will be able to understand it well enough.
*Although, in reality, artificial neurons are nothing like biological neurons, they are just inspired you can say.*
#### **1.1 WORKING OF THE PERCEPTRON**
Now we know how a perceptron looks, let’s see how it works.

Perceptron accepts only binary input i.e., 1 or 0 and similarly, it also outputs in binary. So, if x1, x2, and x3 are input to a perceptron they all can be either a 1 or 0.
Do you see those w1, w2, and w3 in the image? Those are called ***“weights”***, we will talk about them in a bit.
The perceptron works by taking the sum of inputs with the product of their respective weights and then comparing it to the ***threshold value***, so the output is 0, 1 depending on whether the weighted sum( ∑wi.xi ) is greater or less than the threshold value. So, the output of the above figure will be determined by ∑wi.xi = ***“x1.w1 + x2.w2 + x3.w3”*** which is then compared to the threshold value to produce output.
Mathematically, it is easier to understand:
$$\sum_{i}w_i.x_i=x1w1+x2w2+x3w3$$
$$\text{output}= \begin{cases} \text{0 if }\sum\limits_i w_i.x_i \le\text{threshold} \cr\text{1 if }\sum\limits_i w_i.x_i >\text{threshold} \end{cases}$$
> *Now to understand perceptron we shall take an example, this example may not be a real application but it will help us understand perceptron easily.*
Now, suppose you want to go to watch a football match this weekend in a stadium in your city. But the tickets are expensive. There are three conditions that determine whether you will go to watch the match or not:
***x1:*** Do you have enough money to buy the ticket?
***x2:*** Is your favourite team playing?
***x3:*** Is the weather good?
If you were to feed these conditions into the perceptron they can only be 0 or 1.
So, let’s say ***you have enough money to buy the ticket*** you will set ***“x1 = 1”*** otherwise you will set ***“x1 = 0”*** and ***if your favourite team is playing*** set ***“x2 = 1”*** otherwise set “x2 = 0” and ***if the weather is good enough to go out*** set ***“x3 = 1”*** else set ***“x3 = 0”.***
Before, feeding these conditions in the perceptron we will also have to adjust ***“weights”***.
So, what are “weights”? In simple words, ***weights*** are the *importance you give to your input conditions.*
So, let’s say the most important condition for you to go watch the match is ***whether you have money to buy the ticket***, because if you don’t have the money you cannot buy the ticket, so you will assign a greater value of weight to it, let’s say ***w1 = 5.***
Now, you also care about whether your ***favourite team is playing or not***, so you assign a weight of ***w2 = 2*** to it.
But, you don’t care if ***the weather is good or bad***, you are a big football fan and you will still go, so you assign a relatively small weight to that, let’s say ***w3 = 1***.
Now, when you put this in equation 1 and equation 2, you will see if you don’t have the money the output will always be ***0*** even if *your favourite team is playing* and the *weather is good* (assuming the threshold to be 3.5)*.* This is because you have assigned the ***largest weight to w1.*** And, if *you have the money to buy the tickets* the perceptron will most probably ***output 1***.
This is how weights are used in perceptron to set the importance or *weightage* of any input. Also, just like weights, the ***threshold value is adjusted manually according to the need.***
As you have observed, the reason why the perceptron outputs only 0 or 1 is the threshold value which arises due to the usage of the ***step function.***
The ***step function*** is used in perceptron, you can see the step function diagrammatically below, and you should be able to understand how it works with perceptron.

***As we can observe, due to*** ***step function*** ***as-soon-as the output is greater than the threshold value perceptron outputs 1 and for any value equal or less than the threshold, perceptron outputs 0.***
By using perceptrons we could build a network to solve any logic, which in turn made perceptrons another form of logic gates. *Why would we need another form of logic gates when we already had those*? This issue stalled the development and the funding of perceptrons.

> *Using the step function resulted in the biggest drawback of the perceptrons. This issue never allowed perceptrons to learn by changing the weights during the execution.*
Later on, we realised that other types of functions can be used in neurons, and that lead to the development of ***the Sigmoid Neuron.***
### **Part 2: MODERN NEURONS**
#### **2.0 DIFFERENCE BETWEEN MODERN NEURONS AND PERCEPTRONS**
Modern neurons are nothing but a slightly improved version of perceptrons, there are two major differences between any modern neuron and a perceptron:
* The output is any fractional value between 0 and 1 unlike perceptrons, which only have two outputs 0 or 1.
* We use various other ***Activation Functions\**** instead of using *step function* as in perceptron.
* A new term ***bias\*\**** is added to the weighted sum and the ***threshold value is replaced by a 0.***
\*\*\*\*\*\*\*The functions used in neurons to implement the logic are called ***Activation Functions*** so *the step function is the activation function of the perceptron* and *the sigmoid function is the activation function of the sigmoid neuron.*
\*\*\*\*\*\*\*\*The threshold value in the equation(∑wi.xi ≥ threshold) is moved to the left of the equation and named “bias” (∑wi.xi + b ≥ 0).
(b ≅ – threshold).
$$output = \begin{cases}0~if~\sum\limits_{i} w_{i}.x_{i} + b \ge 0 \\\1~if~\sum\limits_{i} w_{i}.x_{i} + b < 0\end{cases}$$
Also, we are setting a new variable ***“z”*** to our weighted sum of inputs + bias to make it better to use in formulas:
$$z = \sum_i w_{i}.x_{i}+b$$
#### **2.1 SIGMOID NEURONS**
We have discussed above how a modern neuron is different from a perceptron, now we will talk about how this modern neuron is working better using sigmoid or other activation functions.
We now know all the theory of how a sigmoid neuron is better than a perceptron but I think it’s all a waste until we visualise it, so let’s dive into how a sigmoid function works to understand how it makes a sigmoid neuron more viable than a perceptron.

The above figure shows you how a sigmoid function looks. Unlike, the step function sigmoid function has a much smoother slope.
If you observe Fig 2 above, on the left(marked with red), the sigmoid function(in blue) goes from 0 to 1. *Hence, for any input, it gives an output between 0 and 1.*
Now, let’s try and understand this *mathematically.* The formula for the sigmoid function is given as:
$$sigmoid(z) = \sigma(z) = \frac{1}{1+e^{-z}}$$
We will discuss two cases to understand the sigmoid function.
* ***When the value of “z” is a very large number.***
$$\sigma(large~number) = \frac{1}{1+e^{-(large~number)}} =\frac{1}{1+0} = 1$$
* ***When the value of “z” is a very large*** ***NEGATIVE*** ***number.***
$$\sigma(large~negative~number) = \frac{1}{1+e^{-(large~negative~number)}} =\frac{1}{1+\infty} = 0$$
*The above two equations show that for very large or very small values the output of the sigmoid function is 1 and 0 respectively and for other values, the sigmoid function gives values between 1 and 0.*
So, a sigmoid neuron will look something like this diagrammatically:

It looks very similar to the perceptron we have seen above, just changing the activation function and outputs.
### **Part 3: NEURAL NETWORKS**
#### **3.0 WHAT IS AN ARTIFICIAL NEURAL NETWORK(ANN)**
After understanding Neurons we can take a look at what a Neural Network(NN) is, in simple words, we can say that:
> *An Artificial Neural Network is a network of artificial neurons.*
When we interconnect two or more neurons with each other, that can be called a neural network.

In the above figure, we can see a simple ANN, it consists of 2 layers(because we don’t count the input layer). The input layer gives input to the hidden layer, it’s called a hidden layer because it is neither input or an output layer, the output of the hidden layer is fed into the output layer which computes our final calculation.
If this is a bit tricky to understand don’t worry, we will discuss how an ANN works in detail in the next chapter.
*An ANN is also called simply a Neural Network.*
#### **3.1 ARCHITECTURE OF A NEURAL NETWORK**

The Neural Networks are designed to resemble the human brain, the ANNs are a simple model that is formed by joining the appropriate number of neurons in order to solve a classification problem or to find patterns in the data.
In the above figure, we can observe a 3-layer Neural Network. As we can observe there is one input layer, two hidden layers, and one output layer.
This is a three-layered Neural Network because we *never count the Input Layer* to be a part of the Neural Network layers.
The hidden layers are called hidden just because they are neither the input layer nor the output layer. Or, we can say that the user doesn’t interact with the hidden layer directly and therefore it is called a hidden layer.
Any number of layers having any number of neurons can be used in any respective layer to achieve the desired goal. For example, the output layer can have two or more neurons instead of one for any different neural network.
This concludes the Introduction to Neural Networks, to read more about these topics follow some of the references below.
***References:***
* [***Comprehensive Introduction to Neural Network Architecture***](https://web.archive.org/web/20211008124809/https://towardsdatascience.com/comprehensive-introduction-to-neural-network-architecture-c08c6d8e5d98)
* [***Neural Networks and Deep Learning online book by Michael Nielsen***](https://web.archive.org/web/20211008124809/http://neuralnetworksanddeeplearning.com/)
|
<script setup>
import { onMounted, reactive, ref } from "vue";
import {
getFirestore,
collection,
query,
where,
// orderBy,
// limit,
// startAt,
// endAt,
getDocs,
} from "firebase/firestore";
import { UserFirebase } from "@/firebase/UserFirebase.js";
import SpinnerGif from "../components/SpinnerGif.vue";
const firebaseConfig = UserFirebase.UserFirebaseConfig();
// const firebaseAuth = getAuth(firebaseApp);
const db = getFirestore(firebaseConfig.firebaseApp);
// console.log(db);
const stores = reactive({
data: [],
});
const loading = ref(false);
const errorMessage = ref("");
onMounted(async () => {
try {
loading.value = true;
const storeCollection = collection(db, "stores");
const dataQuery = query(
storeCollection,
where("storeAddress", ">=", "jl b"),
where("storeAddress", "<", "jl b" + "z")
// orderBy("storeAddress"),
// startAt("jl bupati"),
// endAt("jl bupati" + "\uf8ff")
// limit(5)
);
const dataDocs = await getDocs(dataQuery);
if (!dataDocs) {
errorMessage.value = "Tidak ada data";
}
// dataDocs.forEach((doc) => {
// test.data.push({ id: doc.id, ...doc.data() });
// });
stores.data = dataDocs.docs.map((doc) => doc.data());
loading.value = false;
} catch (error) {
errorMessage.value = error.message;
console.log(errorMessage.value);
loading.value = false;
}
});
</script>
<template>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card shadow my-4">
<!-- <div class="card-header">
Featured
</div> -->
<div class="card-body text-center">
<h5 class="card-title">CARI DATA</h5>
<form action="">
<div class="row g-3 my-3 justify-content-center">
<div class="col-md-3">
<select
class="form-select"
aria-label="Default select example"
>
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-md-3">
<input
type="text"
class="form-control"
placeholder="First name"
aria-label="First name"
/>
</div>
<div class="col-md-1 ps-2 text-start">
<button type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
</div>
<!-- <div class="card-footer text-muted">
2 days ago
</div> -->
</div>
</div>
<div class="col-12" v-if="loading">
<SpinnerGif />
</div>
<div class="col-12 text-center" v-if="errorMessage">
<p class="fw-bold text-danger">{{ errorMessage }}</p>
</div>
<div class="col-12" v-if="!loading && stores.data.length > 0">
<div class="row mx-1 my-4 border shadow">
<h5 class="mt-3">Contoh Data</h5>
<div
class="card m-3"
style="width: 18rem"
v-for="(store, index) in stores.data"
:key="index"
>
<!-- <img src="..." class="card-img-top" alt="..."> -->
<img alt="Vue logo" class="card-img-top" src="@/assets/logo.svg" />
<div class="card-body">
<h6 class="card-title">{{ store.storeName }}</h6>
<p class="card-text">{{ store.storeDescription }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
|
// Challenge 3
// Rewrite the 'calcAverageHumanAge' function from Challenge #2, but this time as an arrow function, and using chaining!
// Test data:
// § Data1:[5,2,4,1,15,8,3] § Data2:[16,6,10,5,6,1,4]
const calcAverageHumanAge = (ages) => {
const average = ages
.map((age) => {
if (age <= 2) {
return 2 * age;
} else {
return 16 + age * 4;
}
})
.filter((age) => {
return age > 18;
})
.reduce((acc, age, i, arr) => {
return acc + age / arr.length;
}, 0);
return average;
};
console.log(calcAverageHumanAge([5, 2, 4, 1, 15, 8, 3]));
|
Alchemical Finances - Manual Personal Finances
Alpha Version 1.7 - 20200909
Beaker Labs llc. [Comming? Maybe? Different Name?]
------------------------------------------------------------------
Purpose to Developer:
------------------------------------------------------------------
The information provided in the next section will outline the functional purpose of the project and explain the original inspiration for the overall program. The purpose
behind the project for me the developer is to use this program to teach myself to code in python and the associated skills. Many aspects of the ledgers developed has steamed
from either a need to learn a new skill, or in an attempt to put a new skill into practice. This project provides a great canvas to try many different skills such as
--- General Python Code and OOP
--- SQLlite
--- Numpy, Pandas, Matplotlib
--- PyQt5
--- Reportlab (Pdf Generator)
--- and more.
------------------------------------------------------------------
Description / Purpose of the Project:
------------------------------------------------------------------
--- The project is designed to replace the use of Microsoft Excel for the purposes of tracking a users Personal Finances
without the need to move to a program like Mint.com / Quicken / Personal Capital ect. This provides a few benefits such as:
--- -- [A] No 2nd/3rd party Data Mining of user information
--- -- [B] All Data is currently stored on the Users Computer only
--- -- [C] No Automatically filled ledgers
--- -- [D] Ability to attached Invoices/Receipts to all transactions.
--- -- [#] Future features are planned [See Bottom for mini pipeline]
--- The program is built on the concept that people understand their finances better when they interact with them rather than watch them.
Having the user manually input transactions helps them pay attention to their exspenses and helps them feel in control. The future addition of
graphs/generated budgets will reinforce this. [Generated budgets will be built from past input data by user selected Categories. Then allow the user to build the following months budget]
------------------------------------------------------------------
Request to Testers
------------------------------------------------------------------
--- Please break my program! Find where my coding needs some work and could benefit from some additional attention. Some things to consider
--- -- - Test User Inputs, Creating New Accounts, Posting/Selecting/Updating/Deleting Transactions, account details ect. Basically everything at this point.
--- Critique the design and concept. At heart the project is meant for me to replace excel but I would like to share to those interested.
------------------------------------------------------------------
Pre-Requisites:
------------------------------------------------------------------
--- Current Design should not require the installation of any additional software. The .exe file should take work independandtly
--- PyQt5 5.11.2 and Python 3.8 used to code the program
------------------------------------------------------------------
Installation
------------------------------------------------------------------
Python
--- 1 -- Download all files in the repository.
--- 2 -- Load the program from the Executable.pyw file.
--- -- -- Be sure to check the Requirements.txt for all associated dependancies required for this program to opperate properly.
------------------------------------------------------------------
Create New User
------------------------------------------------------------------
--- 1 -- Click New Profile
--- 2 -- User Profile is not case sensitive. Everything will be made lowercase.
--- 3 -- Password must be more than 6 characters long and must be alphanumeric.
--- -- -- Unallowed symbols: ["~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "=", ":",
"+", "<", "?", ";", "'", "[", "]", "{", "}", '"', "-", ".", ","]
--- 4 -- Submit new profile
--- 5 -- Cancel out of the new profile screen
--- 6 -- Login
------------------------------------------------------------------
User Manual
------------------------------------------------------------------
--- The file USER_MANUAL.pdf can be found in the same directory as this README.txt.
--- The User Manual will include images and full instructions/conceptual comments about the program.
--- The User Manual will be accessable from within the program as well.
------------------------------------------------------------------
Data Storage
------------------------------------------------------------------
--- All User information will be stored locally on the system in the directory the program was installed on. All files will be created within the "dist/Executable" directory
--- if you move the program be sure to move the data and receipt files as well or the program will create new ones.
--- User data is stored in the data directory
--- Receipts are stored in the Receipts directory by profile name then account ledger
------------------------------------------------------------------
Pipeline Production - Overview room to expand/Change
------------------------------------------------------------------
~~ Obsolete: Project development has mostly cooled down. Still many things that an be done and implimented.
~~ Focus has shifted to learning Data Science. Which would be useful in upgrades to this program. Like Graphing Category Spending.
--- 1 -- Equity and Retirement Ledger [COMPLETED]
--- 2 -- Summary Tab [COMPLETED]
--- -- Archive Tab [COMPLETED]
--- -- About Tab [COMPLETED]
--- -- User Manual [COMPLETED]
--- 3 -- Saving databases - Program Creates a temp file, then saves over the primary .db File
--- 4 -- Generating Printable Reports [COMPLETED - Summary Report]
--- 5 -- CSV exporting
--- 6 -- User Data Back-up
--- 7 -- Ledger to track Large Exspense Purchases
--- 8 -- Ledger to track Long Term Projects
--- 9 -- Work on Ui to adjust to user display. [Completed?]
--- 10 -- Rebrand website to destribute program
-- -- Purchase Commercial Version of PyQt5
-- -- Find Initial Beta Testers
-- -- Will make Visual instructions
-- -- Include Blog
-- -- Comparison to Mint.com and Personal Capital (Maybe Quicken)
--- 11 -- Graphs for budgeting [Inprogress] and Net Worth Tracking [COMPLETED]
--- 12 -- Expand Receipt Display to have a few more features
--- 13 -- Encryption
--- 14 -- User E-mail Address to reset lost passwords
--- 15 -- Explore taking the program to server/cloud storage
--- 16 -- Explore E-mail notifications
-- -- User Set reminders
-- -- Bills Due? Maintence Due? ect?
--- 17 -- Explore Andriod app
-- Maybe -- Webscrapping some Equity Data -- Unsure at this time if i will dive into webscrapping [Found API for Equity]
-- Maybe -- Ledger to track subscriptions
|
package todolist.todo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import todolist.exceptions.ResourceAlreadyExistsException;
import todolist.exceptions.ResourceNotFoundException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
@SpringBootTest(classes=TodoJPAService.class)
public class TodoServiceTest {
@Autowired
private TodoService todoService;
@MockBean
private TodoRepository todoRepository;
private List<Todo> todos;
@BeforeEach
void setUp() {
todos = new ArrayList<>(){{
add(new Todo(1L,"Test1", Statut.ACCOMPLIE ,"C'est le test numéro 1", Timestamp.from(Instant.now())));
add(new Todo(2L, "Test2", Statut.ENCOURS ,"C'est le test numéro 2", Timestamp.from(Instant.now())));
add(new Todo(3L, "Test3", Statut.ENCOURS ,"C'est le test numéro 3", Timestamp.from(Instant.now())));
}};
when(todoRepository.findAll()).thenReturn(todos);
}
@Test
void whenGettingAll_shouldReturn3() {
assertEquals(3, todoService.getAll().size());
}
@Test
void whenGettingById_shouldReturnIfExists_andBeTheSame() {
when(todoRepository.findById(1L)).thenReturn((Optional.of(todos.get(0))));
when(todoRepository.findById(12L)).thenReturn((Optional.empty()));
assertAll(
() -> assertEquals(todos.get(0), todoService.getById(1L)),
() -> assertThrows(ResourceNotFoundException.class, () -> todoService.getById(12L))
);
}
@Test
void whenCreating_ShouldReturnSame() {
Todo toCreate = new Todo(6L, "Test6",Statut.ACCOMPLIE ,"C'est le test numéro 4", Timestamp.from(Instant.now()));
assertEquals(toCreate, todoService.create(toCreate));
}
@Test
void whenCreatingWithSameId_shouldReturnEmpty() {
Todo same_todo = todos.get(0);
assertThrows(ResourceAlreadyExistsException.class, ()->todoService.create(same_todo));
}
@Test
void whenUpdating_shouldModifyTodo() {
Todo initial_todo = todos.get(2);
Todo new_todo = new Todo(initial_todo.getId(), "Test2Update", initial_todo.getStatut(),initial_todo.getContenu(),Timestamp.from(Instant.now()));
todoService.update(new_todo.getId(), new_todo);
Todo updated_todo = todoService.getById(initial_todo.getId());
assertEquals(new_todo, updated_todo);
assertTrue(todoService.getAll().contains(new_todo));
}
@Test
void whenUpdatingNonExisting_shouldThrowException() {
Todo untodo = todos.get(2);
assertThrows(ResourceNotFoundException.class, ()->todoService.update(75L, untodo));
}
@Test
void whenDeletingExistingTodo_shouldNotBeInTodosAnymore() {
Todo todo = todos.get(1);
Long id = todo.getId();
todoService.delete(id);
assertFalse(todoService.getAll().contains(todo));
}
@Test
void whenDeletingNonExisting_shouldThrowException() {
Long id = 68L;
assertThrows(ResourceNotFoundException.class, ()->todoService.delete(id));
}
}
|
package com.example.shipping.presentation.detailsorderscreen
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import com.example.shipping.R
import com.example.shipping.domain.module.Product
@Composable
fun ItemDetails(
item: Product
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 15.dp, bottom = 5.dp, start = 15.dp, end = 15.dp)
.height(100.dp)
.border(1.dp, Color.Black, RoundedCornerShape(10.dp))
.padding(10.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
OrderData(item)
}
}
@OptIn(ExperimentalGlideComposeApi::class)
@Composable
fun OrderData(
data: Product
) {
Row(
modifier = Modifier
.fillMaxHeight(),
) {
Box(
modifier = Modifier
.fillMaxHeight(),
contentAlignment = Alignment.Center
) {
GlideImage(
model = data.product_img,
contentDescription = "loadImage",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(width = 70.dp, height = 80.dp)
) {
it.error(R.drawable.ic_launcher_foreground)
.placeholder(R.drawable.ic_launcher_background)
.load(data.product_img)
}
}
Column(
modifier = Modifier
.fillMaxHeight()
.padding(start = 10.dp),
verticalArrangement = Arrangement.SpaceEvenly
) {
Column {
Text(
text = data.product_name,
fontSize = 12.sp,
maxLines = 2,
fontFamily = FontFamily(Font(R.font.poppins_bold)),
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth(0.5f)
)
Text(
text = "${data.product_price}$",
fontSize = 12.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
Row {
Text(
text = "Quantity:",
fontSize = 10.sp,
overflow = TextOverflow.Ellipsis,
)
Text(
text = "${data.product_count}",
fontSize = 10.sp,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.padding(start = 7.dp),
)
}
}
}
}
|
/*
MIT License
Copyright (c) 2016 Mariano Trebino
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "allocators/PoolAllocator.hpp"
#include <assert.h>
#include <stdint.h>
#include <stdlib.h> /* malloc, free */
#include <algorithm> //max
#include <sstream>
namespace z1dg {
PoolAllocator::PoolAllocator(std::size_t nChunks, std::size_t chunkSize) {
std::stringstream ss("Chunk size must be greater than or equal to ");
ss << sizeof(Node);
assert(chunkSize >= sizeof(Node) && ss.str().c_str());
this->nChunks = nChunks;
this->chunkSize = chunkSize;
startPtr = malloc(this->nChunks * this->chunkSize);
this->Reset();
}
PoolAllocator::~PoolAllocator() {
free(startPtr);
}
void *PoolAllocator::Allocate() {
Node * freePosition = this->freeList.pop();
assert(freePosition != nullptr && "The pool allocator is full");
return static_cast<void *>(freePosition);
}
std::size_t PoolAllocator::GetChunkSize(void) {
return this->chunkSize;
}
void PoolAllocator::Free(void * ptr) {
this->freeList.push((Node *) ptr);
}
void PoolAllocator::Reset() {
// Create a linked-list with all free positions
for (std::size_t i = 0; i < this->nChunks; ++i) {
void *address = (int8_t *) this->startPtr + i * this->chunkSize;
this->freeList.push((Node *) address);
}
}
}
|
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/paper-card/paper-card.html">
<link rel="import" href="../bower_components/neon-animation/neon-animation-runner-behavior.html">
<link rel="import" href="../bower_components/neon-animation/animations/fade-in-animation.html">
<link rel="import" href="../bower_components/neon-animation/animations/scale-up-animation.html">
<link rel="import" href="../bower_components/neon-animation/animations/fade-out-animation.html">
<link rel="import" href="../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="./listen-campaigns.html">
<dom-module id="notif-campaign">
<template>
<style>
:host paper-card {
width: 100%;
position: relative;
margin-bottom: 20px;
}
</style>
<div class="col-md-4 col-lg-3 col-sm-6">
<paper-card on-click="edit" heading="{{campaign.name}}">
<div class="card-content">{{campaign.account}}</div>
<div class="card-actions">
<paper-button >Some action</paper-button>
</div>
</paper-card>
</div>
<paper-dialog id="dialog" entry-animation="scale-up-animation" exit-animation="fade-out-animation" modal="true" withBackdrop="true">
<h2>{{ campaign.name }}</h2>
<paper-dialog-scrollable>
Lorem ipsum...
</paper-dialog-scrollable>
<div class="buttons">
<paper-button dialog-dismiss>Cancel</paper-button>
<paper-button dialog-confirm>Accept</paper-button>
</div>
</paper-dialog>
</template>
<script>
Polymer({
is: 'notif-campaign',
behaviors: [
Polymer.NeonAnimationRunnerBehavior,
HighlightBehavior
],
properties: {
campaign: Object,
animationConfig: {
value: function(){
return {
entry: {
name: 'fade-in-animation',
node: this,
}
}
}
},
},
listeners: {
'neon-animation-finish': '_onNeonAnimationFinish'
},
ready: function(){
// console.log(this.isHighlighted);
this.playAnimation('entry');
},
_onNeonAnimationFinish: function(){
// console.log('test');
},
updateCampaign: function(campaign) {
if (this.campaign.firebase_uid == campaign.firebase_uid) {
// console.log(campaign);
this.campaign = campaign;
}
},
edit: function(){
this.$.dialog.open();
}
});
</script>
</dom-module>
|
%% Reading data from an UFF file recorded with the Verasonics CPWC_L7 example
%
% In this example we show how to read channel and beamformed data from a
% UFF (Ultrasound File Format) file recorded with the Verasonics example.
% You will need an internet connectionto download data. Otherwise, you can
% run the *CPWC_L7.m* Verasonics example so the file 'L7_CPWC_193328.uff'
% is in the current path.
%
% _by Alfonso Rodriguez-Molares <alfonso.r.molares@ntnu.no>
% and Ole Marius Hoel Rindal <olemarius@olemarius.net>_
%
% $Last updated: 2017/09/15$
%% Checking the file is in the path
%
% To read data from a UFF file the first we need is, you guessed it, a UFF
% file. We check if it is on the current path and download it from the USTB
% websever.
% data location
url='http://ustb.no/datasets/'; % if not found data will be downloaded from here
filename='L7_CPWC_193328.uff';
% checks if the data is in your data path, and downloads it otherwise.
% The defaults data path is under USTB's folder, but you can change this
% by setting an environment variable with setenv(DATA_PATH,'the_path_you_want_to_use');
tools.download(filename, url, data_path);
%% Checking what's inside
%
% Now that the file is in the machine we can start loading data. The first
% would be to check what is in there with the *uff.index* function
uff.index([data_path filesep filename],'/',true);
%%
% Let's read the channel data,
channel_data=uff.read_object([data_path filesep filename],'/channel_data');
%%
%
% define a scan
scan=uff.linear_scan();
scan.x_axis = linspace(channel_data.probe.x(1),channel_data.probe.x(end),256).';
scan.z_axis = linspace(0,50e-3,256).';
%%
%
% and beamform
mid=midprocess.das();
mid.dimension = dimension.both;
mid.channel_data=channel_data;
mid.scan=scan;
mid.transmit_apodization.window=uff.window.none;
mid.transmit_apodization.f_number=1.7;
mid.receive_apodization.window=uff.window.none;
mid.receive_apodization.f_number=1.7;
b_data2=mid.go();
b_data2.plot();
|
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('🟢 App Online');
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
// Create csv with headers
const csvWriter = createCsvWriter({
path: 'user-messages.csv',
header: [
{id: 'message', title: 'Message'}
]
});
app.post('/saveMessage', (req, res) => {
const userMessage = req.body.user_message;
console.log('Received message:', userMessage);
const records = [
{message: userMessage}
];
// Save user message to csv
csvWriter.writeRecords(records)// returns a promise
.then(() => {
console.log('...Done');
});
// Send a response back to the client
res.status(200).send({ message: 'Message received successfully' });
});
|
<form>
<div class="form-group">
<ion-item>
<ion-label position="floating" for="name">Name</ion-label>
<ion-input
ngModel name="name"
id="name"
required
minlength="3"
maxlength="10"
#name=ngModel
type="text"
class="form-control"></ion-input>
<div class="alert-danger" *ngIf="name.touched && name.invalid">
<div class="alert-danger" *ngIf="name.errors.required">
Name is required
</div>
<div class="alert-danger" *ngIf="name.errors.minlength">
Name has to have at least {{name.errors.minlength.requiredLength}} characters
</div>
</div>
</ion-item>
</div>
<div class="from-group">
<ion-item>
<ion-label position="floating" for="password">Password</ion-label>
<ion-input
ngModel
name="password"
id="password"
required
minlength="3"
maxlength="10"
#password=ngModel
type="password"
class="form-control"></ion-input>
<div class="alert alert-danger" *ngIf="password.touched && password.invalid">
<div class="alert-danger" *ngIf="password.errors.required">
Password is required
</div>
<div class="alert-danger" *ngIf="password.errors.minlength">
Password has to have at least {{password.errors.minlength.requiredLength}} characters
</div>
</div>
</ion-item>
</div>
<ion-item>
<div class="alert-danger">
<ion-text>
{{message}}
</ion-text>
</div>
</ion-item>
<div class="navigation-link">
<ion-button [disabled]="!name.valid || !password.valid" (click)="login(name.value, password.value)">Login</ion-button>
</div>
<div class="navigation-link">
<ion-button [routerLink]="'../register'">Register</ion-button>
</div>
</form>
|
import { motion, useScroll } from 'framer-motion';
import { useRef } from 'react';
import { getImgUrl } from './getImgUrl';
import { useParallax } from './useParallax';
import './Section.css';
type Props = {
id: string;
};
export function Section({ id }: Props) {
const ref = useRef(null);
const { scrollYProgress } = useScroll({
target: ref,
offset: ['end start', 'start end'],
});
const yH1 = useParallax(scrollYProgress, '0%', '-100%');
const yImg = useParallax(scrollYProgress, '-50%');
// useMotionValueEvent(yH1, 'change', (v) => console.log(id, v));
return (
<section>
{/* this is the scroll-reference for the scroll-progress. For the scroll-progress-offset to work, the target and container cannot be in a parent-child relationship */}
<div ref={ref} />
<motion.img style={{ y: yImg }} src={getImgUrl(id)} alt={id} />
<motion.h1 style={{ y: yH1 }}>{`This is section ${id}`}</motion.h1>
</section>
);
}
|
---
layout: "codefresh"
page_title: "Provider: Codefresh"
sidebar_current: "docs-codefresh-index"
description: |-
The Codefresh provider is used to manage Codefresh resources.
---
# {{ .ProviderShortName | title }} Provider
The {{ .ProviderShortName | title }} Provider can be used to configure [Codefresh](https://codefresh.io/) resources - pipelines, projects, accounts, etc using the [Codefresh API](https://codefresh.io/docs/docs/integrations/codefresh-api/).
## Authenticating to Codefresh
The Codefresh API requires the [authentication key](https://codefresh.io/docs/docs/integrations/codefresh-api/#authentication-instructions) to authenticate.
The key can be passed either as the provider's attribute or as environment variable - `CODEFRESH_API_KEY`.
{{ .SchemaMarkdown | trimspace }}
## Managing Resources Across Different Accounts
The Codefresh API only allows one to operate with the entities in the account tied to the API Key the provider is configured for.
To be able to operate with entities in different accounts, you should create a new key in the relevant account and use providers [aliases](https://www.terraform.io/docs/configuration/providers.html#alias-multiple-provider-instances).
For example:
```hcl
provider "codefresh" {
api_key = "..."
}
provider "codefresh" {
api_key = "..."
alias = "acme-dev"
}
resource "codefresh_pipeline" "pipeline" {
... # Omited for brevity
}
resource "codefresh_pipeline" "pipeline-dev" {
provider = codefresh.acme-dev
... # Omited for brevity
}
```
|
__kupfer_name__ = _("Google Search")
__kupfer_actions__ = ("Search", )
__description__ = _("Search Google with results shown directly")
__version__ = ""
__author__ = "Ulrik Sverdrup <ulrik.sverdrup@gmail.com>"
import urllib
from kupfer.objects import Action, Source, Leaf
from kupfer.objects import TextLeaf, UrlLeaf
try:
import cjson
json_decoder = cjson.decode
except ImportError:
import json
json_decoder = json.loads
SEARCH_URL = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
class Search (Action):
def __init__(self):
Action.__init__(self, _("Google Search"))
def is_factory(self):
return True
def activate(self, leaf):
return SearchResults(leaf.object)
def item_types(self):
yield TextLeaf
def get_description(self):
return __description__
class CustomDescriptionUrl (UrlLeaf):
def __init__(self, obj, title, desc):
UrlLeaf.__init__(self, obj, title)
self.description = desc
def get_description(self):
return self.description
class SearchResults (Source):
def __init__(self, query):
Source.__init__(self, _('Results for "%s"') % query)
self.query = query
def repr_key(self):
return self.query
def get_items(self):
query = urllib.urlencode({'q': self.query})
search_response = urllib.urlopen(SEARCH_URL + query)
ctype = search_response.headers.get("content-type") or ""
parts = ctype.split("charset=", 1)
encoding = parts[-1] if len(parts) > 1 else "UTF-8"
search_results = search_response.read().decode(encoding)
search_response.close()
results = json_decoder(search_results)
data = results['responseData']
more_results_url = data['cursor']['moreResultsUrl']
total_results = data['cursor'].get('estimatedResultCount', 0)
for h in data['results']:
yield UrlLeaf(h['url'], h['titleNoFormatting'])
yield CustomDescriptionUrl(more_results_url,
_('Show More Results For "%s"') % self.query,
_("%s total found") % total_results)
def provides(self):
yield UrlLeaf
|
/**
* ************************************
*
* @module Main
* @author Tu Pham
* @date 1-3-2022
* @description MovieModal component to display detailed information within the Modal component about the movie when Modal is triggered
* ************************************
*/
import React from 'react';
import {setDate} from '../constants/date';
const MovieModal = (props) =>{
//language const to convert server lang data into readable data
const language = { en: 'English', zh: 'Chinese'};
let displayImg = <div className="movie-modal-img" style={{background: 'black'}} ></div>;
if(props.movie.backdrop_path===null) displayImg = <div className="movie-modal-img" style={{background: 'black'}} ></div>;
else displayImg = <div className="movie-modal-img" style={{backgroundImage: `url("https://www.themoviedb.org/t/p/w220_and_h330_face${props.movie.backdrop_path}")`}} ></div>;
return <div className="movie-modal">
{displayImg}
<div className="movie-modal-detail">
<h3>Title: {props.movie.title}</h3>
<div><b>Original Title: </b>: {props.movie.original_title} </div>
<div><b>Release Date: </b>: {setDate(props.movie.release_date)}</div>
<div><b>Original Language: </b>: {language[props.movie.original_language]}</div>
<div><b>Overview</b>: {props.movie.overview}</div>
</div>
</div>;
};
export default MovieModal;
|
package oodb2324_20.savingmoneyunina.Controller;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.chart.PieChart;
import oodb2324_20.savingmoneyunina.BoundaryController.New.NewCategoryController;
import oodb2324_20.savingmoneyunina.BoundaryController.New.NewMoneyboxController;
import javafx.scene.chart.XYChart;
import oodb2324_20.savingmoneyunina.BoundaryController.New.NewTransactionController;
import oodb2324_20.savingmoneyunina.BoundaryController.New.NewWalletController;
import oodb2324_20.savingmoneyunina.BoundaryController.Page.TransactionPageController;
import oodb2324_20.savingmoneyunina.DAO.CardDAO;
import oodb2324_20.savingmoneyunina.DAO.PostgresImp.PostgresCardDAO;
import oodb2324_20.savingmoneyunina.DAO.PostgresImp.PostgresTransactionDAO;
import oodb2324_20.savingmoneyunina.DAO.PostgresImp.PostgresWalletDAO;
import oodb2324_20.savingmoneyunina.DAO.TransactionDAO;
import oodb2324_20.savingmoneyunina.Entity.*;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TransactionController {
private final TransactionDAO transactionDAO = new PostgresTransactionDAO();
private final CardDAO cardDAO = new PostgresCardDAO();
private static TransactionController instance;
private TransactionController(){}
/**
* Returns the instance of the TransactionController object
* @return TransactionController object
*/
public static TransactionController getInstance(){
if(instance == null){
instance = new TransactionController();
}
return instance;
}
/**
* Removes the instance of the object TransactionController
*/
public static void close(){
instance = null;
}
/**
* Save a new transaction
*
* @param transaction transaction object that has to be saved
* @return Returns true if the Transaction has been saved,false otherwise
*/
public boolean saveTransaction (Transaction transaction){
try {
return transactionDAO.save(transaction);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* Delete a transaction
*
* @param transaction transaction object
* @return Returns true if the transaction has been deleted, false otherwise
*/
public boolean deleteTransaction (Transaction transaction){
try{
return transactionDAO.delete(transaction);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* Saves a transaction with the associated wallet
*
* @param transaction transaction object
* @param wallet wallet object
* @return Returns true if the transaction has been saved with the wallet, false otherwise
*/
public boolean saveInWallet (Transaction transaction, Wallet wallet){
try {
return transactionDAO.saveInWallet(transaction,wallet);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* Retrieves a list of transactions filtered by card
*
* @param card card object
* @return Returns a list of transaction objects
*/
public List<Transaction> getTransactionByCard (Card card){
try {
return transactionDAO.getTransactionByCard(card);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Retrieves a list of transactions filtered by wallet
*
* @param wallet wallet object
* @return Returns a list of transaction objects
*/
public List<Transaction> getTransactionByWallet (Wallet wallet){
try {
return transactionDAO.getTransactionByWallet(wallet);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Retrieves a list of transactions filtered by user
*
* @param user user object
* @return Returns a list of transaction objects
*/
public List<Transaction> getTransactionByUser (User user){
try {
return transactionDAO.getTransactionByUser(user);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* retrieve transactions filtered by a card or a list of cards,a range of dates,and optionally a wallet
* @param startDate LocalDate representing the starting date of the range
* @param endDate LocalDate representing the ending date of the range
* @param pan String representing the selected card
* @param walletName String representing the selected wallet
* @param user User object
* @return Return a list of transactions
* @throws SQLException
*/
public List<Transaction> getTransactionByFilter(LocalDate startDate, LocalDate endDate, String pan, String walletName, User user){
try {
List<Card> cards = new ArrayList<>();
if(pan.equals("Tutte le carte")){
cards = cardDAO.getCardsByUser(user);
}else{
cards.add(cardDAO.getCardInfo(pan));
}
if(walletName.equals("Nessuno")){
return transactionDAO.getTransactionByFilter(startDate, endDate, cards);
}else{
Wallet wallet = new PostgresWalletDAO().getWalletInfo(walletName, user);
return transactionDAO.getTransactionByFilter(startDate, endDate, cards, wallet);
}
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
/**
* Notifies the TransactionPageBoundary that a change has occurred and therefore must reload the transactions
* @param user User object
*/
public void notifyTransactionPageBoundary(User user){
TransactionPageController.getInstance(user).setTransactionTable();
}
/**
* Adds a category to the categories' combobox
*
* @param user User object
* @param category category object
*/
public void modifyTransactionCategory(User user,Category category){
NewTransactionController.getInstance(user).addCategories(category);
}
/**
* Adds a moneybox to the moneyboxes' combobox
*
* @param user User object
* @param moneybox moneybox object
*/
public void modifyTransactionMoneybox(User user,Moneybox moneybox){
NewTransactionController.getInstance(user).addMoneybox(moneybox);
}
/**
* Adds a wallet to the wallets' listview
*
* @param user User object
* @param wallet Wallet object
*/
public void modifyTransactionWallet(User user,Wallet wallet){
NewTransactionController.getInstance(user).addWallet(wallet);
}
/**
* Retrieves data based on the filters, to fill the Pie chart
*
* @param startDate LocalDate representing the starting date of the range
* @param endDate LocalDate representing the ending date of the range
* @param pan String representing the selected card
* @param walletName String representing the selected wallet
* @param user User object
* @return Returns a list of Pie chart data
*/
public List<PieChart.Data> getAmountDataChartForReportPage(LocalDate startDate, LocalDate endDate, String pan, String walletName, User user) {
List<PieChart.Data> dataList = new ArrayList<>();
try {
List<Card> cards = new ArrayList<>();
if(pan.equals("Tutte le carte")){
cards = cardDAO.getCardsByUser(user);
}else{
cards.add(cardDAO.getCardInfo(pan));
}
HashMap<String, Double> categoryList;
if(walletName.equals("Nessuno")){
categoryList = transactionDAO.getAmountByCategory(startDate, endDate, cards);
}else{
Wallet wallet = new PostgresWalletDAO().getWalletInfo(walletName, user);
categoryList = transactionDAO.getAmountByCategory(startDate, endDate, cards, wallet);
}
for(Map.Entry<String, Double> category : categoryList.entrySet()){
dataList.add(new PieChart.Data(category.getKey(), category.getValue()));
}
}catch (SQLException e){
e.printStackTrace();
}
return dataList;
}
/**
* Retrieve earning/loss made in a year
* @param user User object
* @param year int representing the year
* @return Return a List of XYChart representing
*/
public List<XYChart.Data<String, Number>> getAmountDataChartForCardPage(User user, String type, int year) {
List<XYChart.Data<String, Number>> dataList = new ArrayList<>();
if(!user.getCards().isEmpty()){
try {
double totalAmount;
for(int month = 1; month <= 12; month++){
totalAmount = transactionDAO.getAmountByUserAndDate(user, type, year, month);
dataList.add(new XYChart.Data<>(Integer.toString(month), totalAmount));
}
}catch (SQLException e){
e.printStackTrace();
}
}
return dataList;
}
/**
* Retrieves the data to fill the report (max,min,avg earning and loss,starting amount end final amount)
*
* @param startDate LocalDate representing the starting date of the range
* @param endDate LocalDate representing the ending date of the range
* @param pan String representing the selected card
* @param walletName String representing the selected wallet
* @param user User object
* @return Returns a list of Double
*/
public List<Double> getReport(LocalDate startDate, LocalDate endDate,String pan,String walletName,User user){
List<Double> reportData = new ArrayList<>();
try {
if (walletName.equals("Nessuno") && pan.equals("Tutte le carte")) {
reportData.addAll(transactionDAO.getReportAllCards(startDate,endDate,user,"Entrata"));
reportData.addAll(transactionDAO.getReportAllCards(startDate,endDate,user,"Uscita"));
} else if (walletName.equals("Nessuno")){
reportData.addAll(transactionDAO.getReportSingleCard(startDate,endDate,"Entrata",pan));
reportData.addAll(transactionDAO.getReportSingleCard(startDate,endDate,"Uscita",pan));
} else if (pan.equals("Tutte le carte")) {
reportData.addAll(transactionDAO.getReportAllCardsWithWallet(startDate,endDate,user,"Entrata",walletName));
reportData.addAll(transactionDAO.getReportAllCardsWithWallet(startDate,endDate,user,"Uscita",walletName));
} else {
reportData.addAll(transactionDAO.getReportSingleCardWithWallet(startDate,endDate,user,"Entrata",walletName,pan));
reportData.addAll(transactionDAO.getReportSingleCardWithWallet(startDate,endDate,user,"Uscita",walletName,pan));
}
reportData.add(transactionDAO.getAmountByDate(startDate,pan));
reportData.add(transactionDAO.getAmountByDate(endDate,pan));
} catch (SQLException e) {
e.printStackTrace();
}
return reportData;
}
/**
* Show a form for adding a new transaction
* @param user User object
*/
@FXML
public void showNewTransaction(User user){
FXMLLoader loader = new FXMLLoader(getClass().getResource("/oodb2324_20/savingmoneyunina/Fxml/New/NewTransaction.fxml"));
loader.setController(NewTransactionController.getInstance(user));
WindowsSupportController.getInstance().addScene(loader);
}
/**
* Show a form for adding a new moneybox
* @param user User object
*/
@FXML
public void showNewMoneybox(User user){
FXMLLoader loader = new FXMLLoader(getClass().getResource("/oodb2324_20/savingmoneyunina/Fxml/New/NewMoneybox.fxml"));
loader.setController(new NewMoneyboxController(user));
WindowsSupportController.getInstance().addScene(loader);
}
/**
* Show a form for adding a new wallet
* @param user User object
*/
public void showNewWallet(User user) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/oodb2324_20/savingmoneyunina/Fxml/New/NewWallet.fxml"));
loader.setController(NewWalletController.getInstance(user));
WindowsSupportController.getInstance().addScene(loader);
}
/**
* Show a form for adding a new category
* @param user User object
*/
public void showNewCategory(User user){
FXMLLoader loader = new FXMLLoader(getClass().getResource("/oodb2324_20/savingmoneyunina/Fxml/New/NewCategory.fxml"));
loader.setController(new NewCategoryController(user));
WindowsSupportController.getInstance().addScene(loader);
}
}
|
% eeg_latencyur() - transform latency of sample point in the continuous
% data into latencies in the transformed dataset.
%
% Usage:
% >> lat_out = eeg_latencyur( events, lat_in);
%
% Inputs:
% events - event structure. If this structure contain boundary
% events, the length of these events is added to restore
% the original latency from the relative latency in 'lat_in'
% lat_in - sample latency (in point) in the original urEEG.
%
% Outputs:
% lat_out - output latency
%
% Note: the function that finds the original (ur) latency in the original
% dataset using latencies in the current dataset is called
% eeg_urlatency()
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2011-
%
% See also: eeg_urlatency()
% Copyright (C) 2011 Arnaud Delorme, SCCN, INC, UCSD, arno@ucsd.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function latout = eeg_latencyur( events, latin );
if nargin < 2
help eeg_latencyur;
return;
end;
boundevents = { events.type };
latout = latin;
if ~isempty(boundevents) & isstr(boundevents{1})
indbound = strmatch('boundary', boundevents);
if isfield(events, 'duration') & ~isempty(indbound)
for index = indbound'
lowerVals = find(latout > events(index).latency);
latout(lowerVals) = latout(lowerVals)-events(index).duration;
end;
end;
end;
return;
% build array of 0 and 1 (0 no data)
boundevents = { events.type };
latout = latin;
if ~isempty(boundevents) & isstr(boundevents{1})
indbound = strmatch('boundary', boundevents);
if isfield(events, 'duration') & ~isempty(indbound)
currentadd = 0;
points = ones(1, events(end).latency+sum([events(indbound').duration])); % arrays of 1
for index = indbound'
currentlat = events(index).latency+currentadd;
currentdur = events(index).duration;
points(round(currentlat):round(currentlat+currentdur)) = 0;
currentadd = currentadd + currentdur;
end;
end;
end;
8;
|
/**
* @description: remark插件,删除重复的h1 的 Header
* @refer: https://github.com/alvinometric/remark-remove-comments/blob/main/transformer.js
*/
import { visit } from 'unist-util-visit';
export default function remarkRemoveMdLinks() {
return (tree, file) => {
visit(tree, 'heading', (node, index, parent) => {
if (node.depth === 1) {
/**
* {
type: 'heading',
depth: 2,
children: [ { type: 'text', value: 'Nacos常规问题', position: [Object] } ],
position: {
start: { line: 47, column: 1, offset: 1108 },
end: { line: 47, column: 13, offset: 1120 }
}
}
*/
const h1HeaderNode = node.children[0];
if (h1HeaderNode && h1HeaderNode.type === 'text' && h1HeaderNode.value === file.data.astro.frontmatter.title){
parent.children.splice(index, 1);
}
}
});
};
}
|
//
// Copyright (C) 2005-2022 Alfresco Software Limited.
//
// This file is part of the Alfresco Content Mobile iOS App.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
extension SystemSearchViewController: NodeActionsViewModelDelegate,
CreateNodeViewModelDelegate {
func handleCreatedNode(node: ListNode?, error: Error?, isUpdate: Bool) {
if node == nil && error == nil {
return
} else if let error = error {
self.display(error: error)
} else {
if isUpdate {
displaySnackbar(with: String(format: LocalizationConstants.Approved.updated,
node?.truncateTailTitle() ?? ""),
type: .approve)
} else {
displaySnackbar(with: String(format: LocalizationConstants.Approved.created,
node?.truncateTailTitle() ?? ""),
type: .approve)
self.openNodeDelegate?.openNode(with: node)
}
}
}
func handleFinishedAction(with action: ActionMenu?,
node: ListNode?,
error: Error?,
multipleNodes: [ListNode]) {
if let error = error {
self.display(error: error)
} else {
guard let action = action else { return }
if action.type.isCreateActions {
handleSheetCreate(action: action)
}
}
}
func handleSheetCreate(action: ActionMenu) {
switch action.type {
case .createMSWord, .createMSExcel, .createMSPowerPoint,
.createFolder:
listItemActionDelegate?.showNodeCreationDialog(with: action,
delegate: self)
case .createMedia: break
case .uploadMedia: break
case .uploadFiles: break
default: break
}
}
func display(error: Error) {
var snackBarMessage = ""
switch error.code {
case ErrorCodes.Swagger.timeout:
snackBarMessage = LocalizationConstants.Errors.errorTimeout
case ErrorCodes.Swagger.nodeName:
snackBarMessage = LocalizationConstants.Errors.errorFolderSameName
default:
snackBarMessage = LocalizationConstants.Errors.errorUnknown
}
displaySnackbar(with: snackBarMessage, type: .error)
}
func displaySnackbar(with message: String?, type: SnackBarType?) {
if let message = message, let type = type {
let snackBar = Snackbar(with: message, type: type)
snackBar.snackBar.presentationHostViewOverride = view
snackBar.show(completion: nil)
}
}
}
|
<template>
<div class="wrap">
<h1>{{ height }}px</h1>
<div ref="myRef">
<img v-for="i in items" :key="i" :src="i" alt="" srcset="" />
<!-- <h2 v-for="i in items" :key="i">{{ i }}</h2> -->
</div>
</div>
</template>
<script>
import { nextTick, onMounted, reactive, toRefs, ref, watch } from 'vue'
import axios from 'axios'
export default {
setup() {
const state = reactive({
height: 0,
items: []
})
const handleLoad = () => {
axios.get('https://dog.ceo/api/breeds/image/random/3').then(res => {
state.items = res.data.message
})
}
const myRef = ref(null)
watch(
() => state,
(newVal, val) => {
console.log('newVal: ', newVal, val)
nextTick(() => {
console.log('nextTick2')
console.log(myRef.value)
state.height = myRef.value.offsetHeight
})
},
{
deep: true
// immediate: true,
}
)
onMounted(async () => {
await handleLoad()
nextTick(() => {
console.log('nextTick1')
})
})
return {
myRef,
...toRefs(state)
}
}
}
</script>
<style lang="css" scoped>
.wrap img {
width: 300px;
height: 300px;
object-fit: cover;
margin: 5px;
}
</style>
|
import * as _ from "lodash";
import {
createContext,
ReactNode,
useContext,
useReducer,
useCallback,
} from "react";
export type CtaFormPerson = {
name: string;
foodChoice: string;
allergies: string;
};
export type FormState = "input" | "isSending" | "hasSent";
export type CtaFormValues = {
willAttend: boolean;
status: FormState;
numberOfAttendingPeople: number;
people: CtaFormPerson[];
};
export type CtaFormActionType =
| "setNum"
| "setName"
| "setAttending"
| "setIsSending"
| "setHasSent"
| "setFood"
| "setAllergies";
export type CtaFormAction =
| {
type: "setNum";
numberOfAttendingPeople: number;
}
| {
type: "setName";
index: number;
name: string;
}
| {
type: "setAttending";
willAttend: boolean;
}
| {
type: "setHasSent";
}
| {
type: "setIsSending";
}
| {
type: "setFood";
index: number;
food: string;
}
| {
type: "setAllergies";
index: number;
allergies: string;
};
type CtaFormUpdater = (
state: CtaFormValues,
action: CtaFormAction
) => CtaFormValues;
const checkOkIndexOrThrow = (
index: number,
numberOfAttendingPeople: number
) => {
if (index < 0 || numberOfAttendingPeople <= index) {
throw new Error(
`Cannot set attribute when index is ${index}, as only ${numberOfAttendingPeople} are expected`
);
}
};
const setNumPeople = (
state: CtaFormValues,
action: CtaFormAction & { type: "setNum" }
) => {
const nextState = _.cloneDeep(state);
nextState.numberOfAttendingPeople = Math.max(
Math.min(action.numberOfAttendingPeople, 20),
1
);
while (nextState.people.length > nextState.numberOfAttendingPeople) {
nextState.people.pop();
}
while (nextState.people.length < nextState.numberOfAttendingPeople) {
nextState.people.push({
name: "",
foodChoice: "all",
allergies: "",
});
}
return nextState;
};
const setAttending = (
state: CtaFormValues,
action: CtaFormAction & { type: "setAttending" }
) => {
const nextState = _.cloneDeep(state);
nextState.willAttend = action.willAttend;
return nextState;
};
const setHasSent = (
state: CtaFormValues,
action: CtaFormAction & { type: "setHasSent" }
) => {
const nextState = _.cloneDeep(state);
nextState.status = "hasSent";
return nextState;
};
const setIsSending = (
state: CtaFormValues,
action: CtaFormAction & { type: "setIsSending" }
) => {
const nextState = _.cloneDeep(state);
nextState.status = "isSending";
return nextState;
};
const setFood = (
state: CtaFormValues,
action: CtaFormAction & { type: "setFood" }
) => {
const nextState = _.cloneDeep(state);
checkOkIndexOrThrow(action.index, state.numberOfAttendingPeople);
nextState.people[action.index].foodChoice = action.food;
return nextState;
};
const setName = (
state: CtaFormValues,
action: CtaFormAction & { type: "setName" }
) => {
const nextState = _.cloneDeep(state);
checkOkIndexOrThrow(action.index, state.numberOfAttendingPeople);
nextState.people[action.index].name = action.name;
return nextState;
};
const setAllergies = (
state: CtaFormValues,
action: CtaFormAction & { type: "setAllergies" }
) => {
const nextState = _.cloneDeep(state);
checkOkIndexOrThrow(action.index, state.numberOfAttendingPeople);
nextState.people[action.index].allergies = action.allergies;
return nextState;
};
const defaultFunc = (state: CtaFormValues, action: CtaFormAction) => {
throw new Error(`Tried to understand action ${action.type} but could not`);
};
const reducerFunctionMapping: { [key in CtaFormActionType]: CtaFormUpdater } = {
setNum: setNumPeople as CtaFormUpdater,
setName: setName as CtaFormUpdater,
setAttending: setAttending as CtaFormUpdater,
setIsSending: setIsSending as CtaFormUpdater,
setHasSent: setHasSent as CtaFormUpdater,
setFood: setFood as CtaFormUpdater,
setAllergies: setAllergies as CtaFormUpdater,
};
const reducer = (state: CtaFormValues, action: CtaFormAction) => {
const func = reducerFunctionMapping[action.type] || defaultFunc;
return func(state, action);
};
const initialState: CtaFormValues = {
willAttend: true,
status: "input",
numberOfAttendingPeople: 2,
people: [
{
name: "",
foodChoice: "all",
allergies: "",
},
{
name: "",
foodChoice: "all",
allergies: "",
},
],
};
const FormContext = createContext<
| { state: CtaFormValues; dispatch: (action: CtaFormAction) => void }
| undefined
>(undefined);
type FormProviderProps = { children: ReactNode };
export const FormProvider = (props: FormProviderProps) => {
const [state, dispatch] = useReducer(reducer, initialState);
const value = { state, dispatch };
return (
<FormContext.Provider value={value}>
{props.children}
</FormContext.Provider>
);
};
export const useForm = () => {
const context = useContext(FormContext);
if (context === undefined) {
throw new Error("useForm must be used within a FormProvider");
}
const { dispatch } = context;
const setNumPeople = useCallback(
(num: number) => {
dispatch({
type: "setNum",
numberOfAttendingPeople: num,
});
},
[dispatch]
);
const setName = useCallback(
(index: number, name: string) => {
dispatch({
type: "setName",
index,
name,
});
},
[dispatch]
);
const setAllergies = useCallback(
(index: number, allergies: string) => {
dispatch({
type: "setAllergies",
index,
allergies,
});
},
[dispatch]
);
const setFood = useCallback(
(index: number, food: string) => {
dispatch({
type: "setFood",
index,
food,
});
},
[dispatch]
);
const setIsSending = useCallback(() => {
dispatch({
type: "setIsSending",
});
}, [dispatch]);
const setHasSent = useCallback(() => {
dispatch({
type: "setHasSent",
});
}, [dispatch]);
const setAttend = useCallback(
(willAttend: boolean) => {
dispatch({
type: "setAttending",
willAttend,
});
},
[dispatch]
);
return {
...context,
setNumPeople,
setName,
setAllergies,
setFood,
setHasSent,
setAttend,
setIsSending,
};
};
|
const express = require("express");
const path = require("path");
const app = express(); //save express function in an (app) variable
// app.com
// app.com/help
// app.com/about
// app.com/weather
// Define paths for Express config
const publicDirPath = path.join(__dirname, "../public");
const views = path.join(__dirname, "../template");
// Setup handlebars engine and views location
app.set("view engine", "hbs");
app.set("views", views);
// Setup static directory to serve
app.use(express.static(publicDirPath));
// app.com
app.get("/", (req, res) => {
res.render("index", { title: "Ahmed" });
});
// app.com/about
app.get("/about", (req, res) => {
res.render("about", {
title: "about me",
name: "Ahmed Eid",
});
});
// app.com/help
app.get("/help", (req, res) => {
res.render("help", {
name: "Ahmed eid Ali",
info: "Ahmed-eid.com",
});
});
app.listen(3000, () => {
console.log("server is up on port 3000");
});
|
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Plus, Search, View } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { useAppStore } from '@/stores/app';
import RoleService from '@/service/RoleService';
const roleService = new RoleService();
const router = useRouter();
const appStore = useAppStore();
const tableData = reactive({
list: [],
count: 0,
loading: false,
page: 1,
size: 10,
role_name: ''
});
const formDialog = reactive({
visible: false,
title: '',
showSubmitLoading: false
});
const baseData = () => {
return {
id: 0,
role_name: '',
introduce: '',
is_able: 1
};
};
const roleFormRef = ref();
const formData = reactive(baseData());
// 关闭dialog
const closeDialog = () => {
formDialog.visible = false;
formDialog.title = '';
Object.assign(formData, baseData());
}
// 请求表格数据
const getTableData = async () => {
tableData.loading = true;
const { data } = await roleService.getRoleList({
page: tableData.page,
size: tableData.size,
role_name: tableData.role_name
});
tableData.loading = false;
tableData.list = data.list;
tableData.count = data.count;
}
// 当前页变化时
const handleCurrentChange = page => {
tableData.page = page;
getTableData();
}
// 每页显示条数变化时
const handleSizeChange = size => {
tableData.size = size;
getTableData();
}
// 添加
const showAdd = () => {
formDialog.visible = true;
formDialog.title = '添加角色';
}
// 编辑
const showEditDialog = row => {
formDialog.visible = true;
formDialog.title = '编辑角色';
Object.assign(formData, row);
}
// 删除
const handleDelete = id => {
ElMessageBox.confirm(`确定删除该角色吗?`, '提示', {
type: 'warning'
}).then(() => {
roleService.deleteRole(id).then(res => {
ElMessage.success(res.msg);
getTableData();
});
}).catch(() => {});
}
// 搜索
const onSearch = () => {
tableData.page = 1;
getTableData();
}
// 自定义索引
const indexMethod = index => {
return (tableData.page - 1) * tableData.size + index + 1;
}
// 预览下级
const roleTreeDialog = reactive({
title: '预览下级',
visible: false,
loading: false
});
const loadChildrenOfRole = async (node, resolve) => {
roleTreeDialog.loading = true;
let id = 0;
if (node.level > 0) {
id = node.data.id;
}
const { data } = await roleService.getChildrenOfRole(id);
roleTreeDialog.loading = false;
resolve(data.list);
}
// dialog表单提交
const submitForm = async formEl => {
if (!formEl) return;
await formEl.validate(valid => {
if (valid) {
formDialog.showSubmitLoading = true;
roleService.addOrEditRole(formData).then(res => {
ElMessage.success(res.msg);
formDialog.showSubmitLoading = false;
closeDialog();
getTableData();
}).catch(() => {
formDialog.showSubmitLoading = false;
});
} else {
console.log('error submit!');
}
});
}
// 表单验证
const roleFormRule = reactive({
role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
});
onMounted(() => {
getTableData();
});
</script>
<template>
<div class="container">
<div style="display: flex; margin-bottom: 10px;">
<el-input
v-model="tableData.role_name"
placeholder="请输入角色名称"
size="small"
maxlength="50"
clearable
style="width: 200px; margin-right: 12px;"
@keyup.enter.native="onSearch"
/>
<el-button size="small" type="primary" :icon="Search" @click="onSearch">搜索</el-button>
<el-button v-if="appStore.isSuper || appStore.auth.includes('sys.role.add')" size="small" type="primary" :icon="Plus" @click="showAdd">添加</el-button>
<el-button v-if="appStore.isSuper || appStore.auth.includes('sys.role.view.children')" size="small" type="info" :icon="View" @click="roleTreeDialog.visible = true">预览下级</el-button>
</div>
<el-table
v-loading="tableData.loading"
:data="tableData.list"
stripe
style="width: 100%"
row-key="id"
>
<el-table-column type="index" label="序号" width="55" :index="indexMethod" />
<el-table-column prop="role_name" label="角色名称" />
<el-table-column prop="introduce" label="角色介绍" />
<el-table-column prop="adminNums" label="管理员数" />
<el-table-column prop="childrenNums" label="直属下级数" />
<el-table-column prop="authNums" label="权限节点数" />
<el-table-column label="启用状态">
<template #default="scope">
<el-tag v-if="scope.row.is_able === 1" type="success">启用</el-tag>
<el-tag v-else type="danger">禁用</el-tag>
</template>
</el-table-column>
<el-table-column prop="created_at" label="创建时间" />
<el-table-column prop="updated_at" label="最后更新时间" />
<el-table-column label="操作" width="220">
<template #default="scope">
<el-button v-if="appStore.isSuper || appStore.auth.includes('sys.role.edit')" size="small" type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
<el-button v-if="appStore.isSuper || appStore.auth.includes('sys.role.auth.assign')" size="small" type="success" @click="router.push({ path: `/system/role/permission/${scope.row.id}` })">权限分配</el-button>
<el-button v-if="!scope.row.childrenNums && !scope.row.adminNums && (appStore.isSuper || appStore.auth.includes('sys.role.delete'))" size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
background
small
layout="total, sizes, prev, pager, next"
:total="tableData.count"
:page-size="tableData.size"
:page-sizes="[5, 10, 15, 20]"
@size-change="handleSizeChange"
@current-change="handleCurrentChange" />
<!-- form dialog -->
<el-dialog
v-model="formDialog.visible"
:title="formDialog.title"
width="30%"
:before-close="closeDialog"
destroy-on-close
:close-on-click-modal="false">
<el-form :model="formData" ref="roleFormRef" :rules="roleFormRule" label-width="78px">
<el-form-item label="角色名称" prop="role_name">
<el-input v-model="formData.role_name" placeholder="请输入角色名称" clearable />
</el-form-item>
<el-form-item label="角色介绍">
<el-input type="textarea" v-model="formData.introduce" placeholder="请输入角色介绍" clearable />
</el-form-item>
<el-form-item label="启用状态">
<el-radio-group v-model="formData.is_able">
<el-radio :value="1">开启</el-radio>
<el-radio :value="0">关闭</el-radio>
</el-radio-group>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="closeDialog" auto-insert-space>取消</el-button>
<el-button
type="success"
auto-insert-space
@click="submitForm(roleFormRef)"
:loading="formDialog.showSubmitLoading">提交</el-button>
</span>
</template>
</el-dialog>
<!-- tree dialog -->
<el-dialog
v-model="roleTreeDialog.visible"
:title="roleTreeDialog.title"
width="30%"
destroy-on-close
:close-on-click-modal="false">
<el-tree node-key="id" v-loading="roleTreeDialog.loading" lazy :load="loadChildrenOfRole" :props="{ label: 'role_name', isLeaf: 'leaf' }" />
</el-dialog>
</div>
</template>
<style scoped>
.el-pagination {
margin-top: 10px;
}
</style>
|
import Link from "next/link";
import styled from "styled-components";
import { AiOutlineArrowRight } from "react-icons/ai";
import colors from "../../../styles/colors";
import { Article } from "../../../utils/posts";
const PostContainer = styled.a`
display: flex;
flex-direction: column;
gap: 16px;
svg {
display: none;
}
&:hover svg {
display: block;
}
`;
const PostTitle = styled.h2`
font-size: 22px;
`;
const PostExcerpt = styled.span`
font-size: 16px;
line-height: 32px;
`;
const PostCallToAction = styled.b`
display: flex;
align-items: center;
gap: 4px;
font-size: 16px;
`;
const PostsList = styled.div`
display: flex;
flex-direction: column;
gap: 56px;
`;
const ArticleList = ({ articles }: { articles: Article[] }) => (
<PostsList>
{articles.map(({ excerpt, href, title }) => (
<Link key={href} href={href} passHref>
<PostContainer>
<PostTitle>{title}</PostTitle>
{excerpt && <PostExcerpt>{excerpt}</PostExcerpt>}
<PostCallToAction>
Read more <AiOutlineArrowRight color={colors.secondaryText} />
</PostCallToAction>
</PostContainer>
</Link>
))}
</PostsList>
);
export default ArticleList;
|
## Type Constraints
https://developer.hashicorp.com/terraform/language/expressions/type-constraints
Setting List,Maps, Tuples, and Objects
```
terraform {
}
// List
variable "planet" {
type = list
default = ["mars", "earth", "venus", "jupiter"]
}
// Map
variable "names_titles" {
type = map
default = {
"Pratik" = "Sinha"
"Rima" = "Das"
"Sonia" = "Menda"
"Chandan" = "Bera"
}
}
// Object
variable "plans_object" {
type = object({
PlanA = string
PlanB = string
PlanC = string
PlanD = string
})
default = {
"PlanA" = "10 USD"
"PlanB" = "20 USD"
"PlanC" = "30 USD"
"PlanD" = "40 USD"
}
}
// Object
variable "plan" {
type = object({
PlanName = string
PlanAmount = number
PlanStatus = bool
})
default = {
PlanName = "Goa"
PlanAmount = 100
PlanStatus = true
}
}
// Tuples
variable "stores" {
type = tuple([ string, number, bool ])
default = [ "Arambagh", 224, true ]
}
```
Go to `terraform console`
```hcl
var.names_titles OR var.planets OR var.stores OR var.stores
```
##
Here are examples of lists, tuples, maps, and objects in Terraform :
1. List -
An ordered collection of values, accessed by index.
Example :
```
variable "names" {
type = list(string)
default = ["Alice", "Bob", "Charlie"]
}
output "first_name" {
value = var.names[0] # Access the first element
}
```
2. Tuple -
An ordered collection of values, like a list, but with fixed size and potentially mixed types.
Example :
```
variable "coordinates" {
type = tuple([number, number])
default = [10, 20]
}
output "longitude" {
value = var.coordinates[0] # Access the longitude
}
```
3. Map -
An unordered collection of key-value pairs.
Example :
```
variable "tags" {
type = map(string)
default = {
Name = "MyInstance"
Environment = "Production"
}
}
output "environment" {
value = var.tags["Environment"] # Access a value by key
}
```
4. Object
Similar to a map, but with more structure and potentially nested elements.
Example :
```
variable "user" {
type = object({
name = string
email = string
address = object({
street = string
city = string
})
})
}
output "user_city" {
value = var.user.address.city # Access nested properties
}
```
Notes:
Sets are not directly supported in Terraform, but you can often use maps with unique keys to achieve a similar effect.
Terraform doesn't strictly enforce types, but specifying types for variables and arguments is recommended for clarity and consistency.
The for expression can be used to iterate over lists, tuples, maps, and objects.
you can also combine 2 type of data.
Example :
```
variable "ou_to_acount" {
type = list(object({
ou_l3 = string
account = list(object({
name = string
email = string
}))
}))
}
```
|
import {
Controller,
Get,
Param,
Post,
Body,
Put,
Delete,
UsePipes,
ValidationPipe,
Query,
UseFilters,
} from '@nestjs/common';
import { ProductService } from './product.service';
import { DocumentType } from '@typegoose/typegoose';
import { Product } from './product.type';
import { createProductInput, updateProductInput } from './product.input';
import { ApiTags, ApiQuery } from '@nestjs/swagger';
import { ResourceList, ResourcePagination } from 'src/shared/types';
import { InvalidObjectId } from 'src/shared/object-castid.filter';
import { QCExceptionFilter } from 'src/shared/qc.filter';
import { ApiPagination } from 'src/utils/ApiPagination.decorator';
@ApiTags('Products')
@Controller('product')
export class ProductController {
constructor(private readonly productservice: ProductService) {}
@Get()
@ApiPagination()
async index(
@Query() query: ResourcePagination,
): Promise<ResourceList<DocumentType<Product>>> {
return this.productservice.getProducts(query);
}
@Get(':_id')
@UseFilters(InvalidObjectId)
async show(@Param('_id') productId: string): Promise<DocumentType<Product>> {
return this.productservice.getProductById(productId);
}
@Post()
@UsePipes(ValidationPipe)
async store(
@Body() data: createProductInput,
): Promise<DocumentType<Product>> {
return this.productservice.createproduct(data);
}
@Put(':_id')
@UsePipes(ValidationPipe)
@UseFilters(QCExceptionFilter)
async update(
@Body() updatedata: updateProductInput,
@Param('_id') productId: string,
): Promise<DocumentType<Product>> {
return this.productservice.updateproduct(productId, updatedata);
}
@Delete(':_id')
@UseFilters(QCExceptionFilter)
async delete(
@Param('_id') productId: string,
): Promise<DocumentType<Product>> {
return this.productservice.deleteProduct(productId);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.